Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Print Paths from root to all leaf nodes in a binary tree.

Objec­tive: Given a binary tree, Print paths from root to all leaf nodes

Input: A binary tree

Exam­ple:

Print paths from root to all leaf nodes

Print paths from root to all leaf nodes

Approach:

  • Do the pre­Order traversal.
  • Store the cur­rent node in an array, say Path[] and main­tain the length say pathLength.
  • check if you are at leaf node (both the left and right child of par­ent will be null).
  • If not then keep tra­vers­ing by mak­ing recur­sive calls to root.left and root.right. Pass the path and pathLen as para­me­ter so that at each level have its own copy of path and and its length.
  • If you hit the leaf node then print the array.
  • See Code

Com­plete Code:


Out­put :

1 2 4 7
1 3 6 8
1 3 6 9

You may also like...