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

Objective: Given a binary tree, Print paths from root to all leaf nodes

Input: A binary tree


Print paths from root to all leaf nodes

Print paths from root to all leaf nodes


  • Do the preOrder traversal.
  • Store the current node in an array, say Path[] and maintain the length say pathLength.
  • check if you are at leaf node (both the left and right child of parent will be null).
  • If not then keep traversing by making recursive calls to root.left and root.right. Pass the path and pathLen as parameter 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

Complete Code:

Output :

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

Top Companies Interview Questions..-


If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

1 Response

  1. Mahesh says:

    Do inorder traversal and store current path from root, when you reach leaft node, print path

    private static void printPaths(Node root, String s) {
    if(root == null)

    printPaths(root.left, s+”->”;
    if(root.left == null && root.right == null)


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: