Given the roots of a tree. print out all of its root-to-leaf paths one per line..
initialize: pathlen = 0, path /*1000 is some max limit for paths, it can change*/ /*printPathsRecur traverses nodes of tree in preorder */ printPathsRecur(tree, path, pathlen) 1) If node is not NULL then a) push data to path array: path[pathlen] = node->data. b) increment pathlen pathlen++ 2) If node is a leaf node then print the path array. 3) Else a) Call printPathsRecur for left subtree printPathsRecur(node->left, path, pathLen) b) Call printPathsRecur for right subtree. printPathsRecur(node->right, path, pathLen)
Output for the above example will be
1 2 4 1 2 5 1 3
1 2 4 1 2 5 1 3
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Tree Traversals (Inorder, Preorder and Postorder)
- Print all pairs from two BSTs whose sum is greater than the given value
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Check for Children Sum Property in a Binary Tree