Print all root to leaf paths in a binary tree

In this post, we will see how to print all root to leaf paths in binary tree in java.

Root to leaf paths


Algorithm:

Here is simple algorithm to print all root to leaf paths.

  • If root is null , return
  • If left and right child of root is null, we found the leaf node
    • Add node to curretPath
    • Add currentPath to result
  • Add root to current path
  • Traverse left child of root
  • Backtrack
  • Traverse right child of root
  • Backtrack

Code:


Complete java program to print all root to leaf paths

Output of above program:

All paths from root to leaf:
Path 1: 90 10 60
Path 2: 90 10 70
Path 3: 90 50 100
Path 4: 90 50 80 20
Path 5: 90 50 80 30

That’s all about printing all root to leaf paths in a binary tree

Leave a Reply

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