Given a number N which is the total number of nodes in a complete binary tree where nodes are number from 1 to N sequentially level-wise. The task is to write a program to print paths from root to all of the nodes in the Complete Binary Tree.
For N = 3, the tree will be:
1 / \ 2 3
For N = 7, the tree will be:
1 / \ 2 3 / \ / \ 4 5 6 7
Input : 7 Output : 1 1 2 1 2 4 1 2 5 1 3 1 3 6 1 3 7 Input : 4 Output : 1 1 2 1 2 4 1 3
Explanation :- Since, the given tree is a complete binary tree. For every node we can calculate it’s left child as 2*i and right child as 2*i + 1.
The idea is to use a backtracking approach to print all paths. Maintain a vector to store paths, initially push the root node 1 to it, and before pushing the left and right childs print the current path stored in it and then call the function for the left and right childs as well.
Below is the complete implementation of the above approach:
1 1 2 1 2 4 1 2 5 1 3 1 3 6 1 3 7
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.
- Print path from root to a given node in a binary tree
- Print the first shortest root to leaf path in a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Find all root to leaf path sum of a Binary Tree
- Print the path common to the two paths from the root to the two given nodes
- Print common nodes on path from root (or common ancestors)
- Find the path from root to the given nodes of a tree for multiple queries
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U
- Print path between any two nodes in a Binary Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Given a binary tree, print all root-to-leaf paths
- Print all the paths from root, with a specified sum in Binary tree
- Find the maximum sum leaf to root path in a Binary Tree
- Sort the path from root to a given node in a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Maximize count of set bits in a root to leaf path in a binary tree
- Height of a complete binary tree (or Heap) with N nodes
- Sum of the mirror image nodes of a complete binary tree in an inorder way
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.