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
- 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 path between any two nodes in a Binary Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Print the path common to the two paths from the root to the two given nodes
- Find the path from root to the given nodes of a tree for multiple queries
- Sort the path from root to a given node in a Binary Tree
- Find the maximum sum leaf to root 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
- XOR of path between any two nodes in a Binary Tree
- Print common nodes on path from root (or common ancestors)
- Print all the paths from root, with a specified sum in Binary tree
- Given a binary tree, print all root-to-leaf paths
- Shortest path between two nodes in array like representation of binary tree
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.