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

If you want to practice data structure and algorithm programs, you can go through 100+ java coding 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.

Was this post helpful?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *