Given a binary tree, print all the root to leaf paths of the tree. For example: Consider the tree: 1 2 3 4 5 6 7
There will be 4 paths to the from root to the leaves 4, 5, 6 and 7 as given in below output: Output: 1 2 4 1 2 5 1 3 6 1 3 7
Video coming soon!
Subscribe for more updates
Preparing for interviews? IDeserve team is here to help.
Create your profile
Create your profile, and here is what you will get:
1: Interview practice platform.
2: Once you are ready to take the interview, IDeserve team will help you get connected to the best job opportunities.
3: Personalized mentorship from IDeserve team once your interview process has started.
Creation of profile shouldn't take more than 2 minutes.
The algorithm traverses the tree in pre-order manner and uses an array list to store the paths. When a leaf node is reached, the path is printed. path - an array list that stores the current path.
Step 1: Add root data to the array list. Step 2: If root is a leaf, print the path and return. Step 3: Recursively traverse the left subtree. Step 4: Recursively traverse the right subtree.
Note: A new array list is created in the recursive calls (Steps 3 and 4) because we do not want to share the same array list in left and right subtree calls as the paths will be different. We add nodes up to the current path to the array list because the paths up to the current node are common for left and right subtrees.
Support us by whitelisting IDeserve in your ad-blocker.