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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Print all the paths from root, with a specified sum in Binary tree
- Print all k-sum paths in a binary tree
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Print all the Paths of a Binary Tree whose XOR is non-zero
- Print Palindromic Paths of Binary tree
- Count all k-sum paths in a Binary Tree
- Count of paths in given Binary Tree with odd bitwise AND for Q queries
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Sum of lengths of all paths possible in a given tree
- Count number of times each Edge appears in all possible paths of a given Tree
- Root to leaf paths having equal lengths in a Binary Tree
- Count even paths in Binary Tree
- Count of exponential paths in a Binary Tree
- Count of Fibonacci paths in a Binary tree
- Count of root to leaf paths in a Binary Tree that form an AP
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Count root to leaf paths having exactly K distinct nodes in a Binary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Print all root to leaf paths with there relative positions