Program to print path from root to all nodes in a Complete Binary Tree using C++

C++Server Side ProgrammingProgramming

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
raja
Published on 01-Nov-2019 11:01:57
Advertisements