For the below example tree, all root-to-leaf paths are:
10 –> 8 –> 3
10 –> 8 –> 5
10 –> 2 –> 2
Use a path array path to store current root to leaf path. Traverse from root to all leaves in top-down fashion. While traversing, store data of all nodes in current path in array path. When we reach a leaf node, print the path array.
10 8 3 10 8 5 10 2 2
Time Complexity: O(n2) where n is number of nodes.
Please write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem.
Improved By : shweta44
- Double Tree
- Root to leaf path sum equal to a given number
- Linked complete binary tree & its creation
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Construct Tree from given Inorder and Preorder traversals
- HashSet vs TreeSet in Java
- Preorder from Inorder and Postorder traversals
- Count pairs in a binary tree whose sum is equal to a given value x
- Find the maximum node at a given level in a binary tree
- Print nodes in top view of Binary Tree | Set 2