print all paths from root to leaf in a binary tree in java

Previous
Next

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

This is 9th part of java binary tree tutorial.

In this post, we will see about program to print all paths from root to leaf in a binary tree in java.
Below diagram will show all paths  from root to leaf:

Algorithm:

Steps for print all paths from root to leaf are:
  • If node is null then return 0
  • put node.data in array and increment len by 1.
  • If encounterd leaf node(i.e. node.left is null and node.right is null) then print array.
  • Recursively visit left subtree and right subtree

Code for recursion will be:

Lets create java program for counting number of leaf nodes:

Run above program and you will get following output:

Java Binary tree tutorial:

Please go through java interview programs for more such programs.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

3 Comments

  1. John Williams May 2, 2015
  2. tanu June 2, 2015
    • arpitmandliya June 24, 2015

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog