- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to print path from root to all nodes in a Complete Binary Tree using C++
In this tutorial, we will be discussing a program to print the path from the root node of a binary tree to all the other nodes present in the given binary tree.
In this program, we will be given a number N, denoting the number of elements present in the binary tree from 1 to N; 1 being the root node of the binary tree. Therefore, our task is to print all the possible paths from the root node to the various other elements present in the binary tree.
To solve this program, we know that for given node I, its left child can be calculated as 2*i and its right child can be calculated as 2*i+1. We can then use backtracking to store the path of that particular element in a vector and then final print all the possible paths.
Example
#include <iostream> #include <vector> using namespace std; //calculating all the possible paths from the root node void calc_allpath(vector<int> paths, int nth_node, int kth_node){ if (kth_node > nth_node) return; paths.push_back(kth_node); for (int i = 0; i < paths.size(); i++) cout << paths[i] << " "; cout << endl; calc_allpath(paths, nth_node, kth_node * 2); calc_allpath(paths, nth_node, kth_node * 2 + 1); } //printing all the possible paths from the root node void print_allpath(int nth_node){ vector<int> paths; calc_allpath(paths, nth_node, 1); } int main(){ int nth_node = 9; print_allpath(nth_node); return 0; }
Output
1 1 2 1 2 4 1 2 4 8 1 2 4 9 1 2 5 1 3 1 3 6 1 3 7
- Related Articles
- Program to print path from root to a given node in a binary tree using C++
- Program to print the first shortest root to leaf path in a Binary Tree using C++
- Print all leaf nodes of a binary tree from right to left in C++
- Print All Leaf Nodes of a Binary Tree from left to right using Iterative Approach in C++
- Print all full nodes in a Binary Tree in C++
- Print all internal nodes of a Binary tree in C++
- Program to print nodes in the Top View of Binary Tree using C++
- Program to print the longest leaf to leaf path in a Binary tree using C++
- Print path between any two nodes in a Binary Tree in C++ Programming.
- Print the first shortest root to leaf path in a Binary Tree in C++ Programming.
- Print all odd nodes of Binary Search Tree in C++
- Print all even nodes of Binary Search Tree in C++
- Program to print nodes between two given level numbers of a binary tree using C++
- Print Levels of all nodes in a Binary Tree in C++ Programming.
- Print all nodes in a binary tree having K leaves in C++

Advertisements