Open In App

Print path from root to all nodes in a Complete Binary Tree

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Examples: 
 

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 i     we can calculate its 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 children print the current path stored in it and then call the function for the left and right children as well. 
Below is the complete implementation of the above approach:
 

C++

// C++ program to print path from root to all
// nodes in a complete binary tree.
 
#include <iostream>
#include <vector>
using namespace std;
 
// Function to print path of all the nodes
// nth node represent as given node
// kth node represents as left and right node
void printPath(vector<int> res, int nThNode, int kThNode)
{
    // base condition
    // if kth node value is greater
    // then nth node then its means
    // kth node is not valid so
    // we not store it into the res
    // simply we just return
    if (kThNode > nThNode)
        return;
 
    // Storing node into res
    res.push_back(kThNode);
 
    // Print the path from root to node
    for (int i = 0; i < res.size(); i++)
        cout << res[i] << " ";
    cout << "\n";
 
    // store left path of a tree
    // So for left we will go node(kThNode*2)
    printPath(res, nThNode, kThNode * 2);
 
    // right path of a tree
    // and for right we will go node(kThNode*2+1)
    printPath(res, nThNode, kThNode * 2 + 1);
}
 
// Function to print path from root to all of the nodes
void printPathToCoverAllNodeUtil(int nThNode)
{
    // res is for store the path
    // from root to particulate node
    vector<int> res;
 
    // Print path from root to all node.
    // third argument 1 because of we have
    // to consider root node is 1
    printPath(res, nThNode, 1);
}
 
// Driver Code
int main()
{
    // Given Node
    int nThNode = 7;
 
    // Print path from root to all node.
    printPathToCoverAllNodeUtil(nThNode);
 
    return 0;
}

                    

Java

// Java program to print path from root to all
// nodes in a complete binary tree.
import java.util.*;
 
class GFG
{
 
// Function to print path of all the nodes
// nth node represent as given node
// kth node represents as left and right node
static void printPath(Vector<Integer> res,
                    int nThNode, int kThNode)
{
    // base condition
    // if kth node value is greater
    // then nth node then its means
    // kth node is not valid so
    // we not store it into the res
    // simply we just return
    if (kThNode > nThNode)
        return;
 
    // Storing node into res
    res.add(kThNode);
 
    // Print the path from root to node
    for (int i = 0; i < res.size(); i++)
        System.out.print( res.get(i) + " ");
    System.out.print( "\n");
 
    // store left path of a tree
    // So for left we will go node(kThNode*2)
    printPath(res, nThNode, kThNode * 2);
 
    // right path of a tree
    // and for right we will go node(kThNode*2+1)
    printPath(res, nThNode, kThNode * 2 + 1);
     
    res.remove(res.size()-1);
}
 
// Function to print path from root to all of the nodes
static void printPathToCoverAllNodeUtil(int nThNode)
{
    // res is for store the path
    // from root to particulate node
    Vector<Integer> res=new Vector<Integer>();
 
    // Print path from root to all node.
    // third argument 1 because of we have
    // to consider root node is 1
    printPath(res, nThNode, 1);
}
 
// Driver Code
public static void main(String args[])
{
    // Given Node
    int nThNode = 7;
 
    // Print path from root to all node.
    printPathToCoverAllNodeUtil(nThNode);
}
}
 
// This code is contributed by Arnab Kundu

                    

Python3

# Python3 program to print path from root
# to all nodes in a complete binary tree.
 
# Function to print path of all the nodes
# nth node represent as given node kth
# node represents as left and right node
def printPath(res, nThNode, kThNode):
 
    # base condition
    # if kth node value is greater
    # then nth node then its means
    # kth node is not valid so
    # we not store it into the res
    # simply we just return
    if kThNode > nThNode:
        return
 
    # Storing node into res
    res.append(kThNode)
 
    # Print the path from root to node
    for i in range(0, len(res)):
        print(res[i], end = " ")
    print()
 
    # store left path of a tree
    # So for left we will go node(kThNode*2)
    printPath(res[:], nThNode, kThNode * 2)
 
    # right path of a tree
    # and for right we will go node(kThNode*2+1)
    printPath(res[:], nThNode, kThNode * 2 + 1)
 
# Function to print path from root
# to all of the nodes
def printPathToCoverAllNodeUtil(nThNode):
 
    # res is for store the path
    # from root to particulate node
    res = []
 
    # Print path from root to all node.
    # third argument 1 because of we have
    # to consider root node is 1
    printPath(res, nThNode, 1)
 
# Driver Code
if __name__ == "__main__":
 
    # Given Node
    nThNode = 7
 
    # Print path from root to all node.
    printPathToCoverAllNodeUtil(nThNode)
 
# This code is contributed by Rituraj Jain

                    

C#

// C# program to print path from root to all
// nodes in a complete binary tree.
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to print path of all the nodes
// nth node represent as given node
// kth node represents as left and right node
static void printPath(List<int> res,
                    int nThNode, int kThNode)
{
    // base condition
    // if kth node value is greater
    // then nth node then its means
    // kth node is not valid so
    // we not store it into the res
    // simply we just return
    if (kThNode > nThNode)
        return;
 
    // Storing node into res
    res.Add(kThNode);
 
    // Print the path from root to node
    for (int i = 0; i < res.Count; i++)
        Console.Write( res[i] + " ");
    Console.Write( "\n");
 
    // store left path of a tree
    // So for left we will go node(kThNode*2)
    printPath(res, nThNode, kThNode * 2);
 
    // right path of a tree
    // and for right we will go node(kThNode*2+1)
    printPath(res, nThNode, kThNode * 2 + 1);
     
    res.RemoveAt(res.Count-1);
}
 
// Function to print path from root to all of the nodes
static void printPathToCoverAllNodeUtil(int nThNode)
{
    // res is for store the path
    // from root to particulate node
    List<int> res=new List<int>();
 
    // Print path from root to all node.
    // third argument 1 because of we have
    // to consider root node is 1
    printPath(res, nThNode, 1);
}
 
// Driver Code
public static void Main(String []args)
{
    // Given Node
    int nThNode = 7;
 
    // Print path from root to all node.
    printPathToCoverAllNodeUtil(nThNode);
}
}
 
// This code contributed by Rajput-Ji

                    

PHP

<?php
// PHP program to print path from root to all
// nodes in a complete binary tree.
 
// Function to print path of all the nodes
// nth node represent as given node
// kth node represents as left and right node
function printPath($res, $nThNode, $kThNode)
{
    // base condition
    // if kth node value is greater
    // then nth node then its means
    // kth node is not valid so
    // we not store it into the res
    // simply we just return
    if ($kThNode > $nThNode)
        return;
 
    // Storing node into res
    array_push($res, $kThNode);
 
    // Print the path from root to node
    for ($i = 0; $i < count($res); $i++)
        echo $res[$i] . " ";
    echo "\n";
 
    // store left path of a tree
    // So for left we will go node(kThNode*2)
    printPath($res, $nThNode, $kThNode * 2);
 
    // right path of a tree
    // and for right we will go node(kThNode*2+1)
    printPath($res, $nThNode, $kThNode * 2 + 1);
}
 
// Function to print path
// from root to all of the nodes
function printPathToCoverAllNodeUtil($nThNode)
{
    // res is for store the path
    // from root to particulate node
    $res = array();
 
    // Print path from root to all node.
    // third argument 1 because of we have
    // to consider root node is 1
    printPath($res, $nThNode, 1);
}
 
// Driver Code
 
// Given Node
$nThNode = 7;
 
// Print path from root to all node.
printPathToCoverAllNodeUtil($nThNode);
 
// This code is contributed by mits
?>

                    

Javascript

<script>
 
// JavaScript program to print path from root to all
// nodes in a complete binary tree.
 
// Function to print path of all the nodes
// nth node represent as given node
// kth node represents as left and right node
function printPath(res, nThNode, kThNode)
{
    // base condition
    // if kth node value is greater
    // then nth node then its means
    // kth node is not valid so
    // we not store it into the res
    // simply we just return
    if (kThNode > nThNode)
        return;
 
    // Storing node into res
    res.push(kThNode);
 
    // Print the path from root to node
    for (var i = 0; i < res.length; i++)
        document.write( res[i] + " ");
    document.write( "<br>");
 
    // store left path of a tree
    // So for left we will go node(kThNode*2)
    printPath(res, nThNode, kThNode * 2);
 
    // right path of a tree
    // and for right we will go node(kThNode*2+1)
    printPath(res, nThNode, kThNode * 2 + 1);
 
    res.pop()
}
 
// Function to print path from root to all of the nodes
function printPathToCoverAllNodeUtil( nThNode)
{
    // res is for store the path
    // from root to particulate node
    var res = [];
 
    // Print path from root to all node.
    // third argument 1 because of we have
    // to consider root node is 1
    printPath(res, nThNode, 1);
}
 
// Driver Code
 
// Given Node
var nThNode = 7;
 
// Print path from root to all node.
printPathToCoverAllNodeUtil(nThNode);
 
 
</script>

                    

Output: 
1 
1 2 
1 2 4 
1 2 5 
1 3 
1 3 6 
1 3 7

 

Time Complexity: O(N*H) where N is the number of nodes and H is the height of binary tree.
Auxiliary Space: O(H) where H is the height of binary tree.



Similar Reads

Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path
Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path. Examples: Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1,
11 min read
Print path from a node to root of given Complete Binary Tree
Given an integer N, the task is to find the path from the Nth node to the root of a Binary Tree of the following form: The Binary Tree is a Complete Binary Tree up to the level of the Nth node.The nodes are numbered 1 to N, starting from the root as 1.The structure of the Tree is as follows: 1 / \ 2 3 / \ / \ 4 5 6 7 ................ / \ ..........
4 min read
Count nodes having highest value in the path from root to itself in a Binary Tree
Given a Binary Tree, the task is to count the number of nodes in the Binary Tree, which are the highest valued node in the path from the root up to that node. Examples: Input: Below is the given Tree: 3 / \ 2 5 / \ 4 6Output: 4Explanation:Root node satisfies the required condition.Node 5 is the highest valued node in the path (3 -&gt; 5).Node 6 is
8 min read
Count nodes having smallest value in the path from root to itself in a Binary Tree
Given a Binary Tree, the task is to count the number of nodes in the given Binary Tree such that the path from the root to that node contains node with value greater than or equal to that node. Examples: Input: 6 / \ 7 4 / \ / \ 3 7 1 2 Output: 5 Explanation: Root node 6 is considered as its the only node in the path from root to itself. Node 4 has
8 min read
Print the first shortest root to leaf path in a Binary Tree
Given a Binary Tree with distinct values, the task is to print the first smallest root to leaf path. We basically need to print the leftmost root to leaf path that has the minimum number of nodes. Input: 1 / \ 2 3 / / \ 4 5 7 / \ \ 10 11 8 Output: 1 3 5 Input: 1 / \ 2 3 / / \ 40 5 7 \ 8 Output: 1 2 40 Approach: The idea is to use a queue to perform
12 min read
Print the longest path from root to leaf in a Binary tree
Given a binary tree, the task is to print the longest path from the root node to the leaf node. If there are multiple answers print any one of them. Examples: Input: 4 / \ 3 6 / \ 5 7 Output: 4 -&gt; 6 -&gt; 7 Explanation: Longest paths from root to leaf are (4 -&gt; 6 -&gt; 5) and (4 -&gt; 6 -&gt; 7). Print any of them. Input: 1 / \ 2 3 / \ 4 5 \
8 min read
Print path from root to a given node in a binary tree
Given a binary tree with distinct nodes(no two nodes have the same data values). The problem is to print the path from root to a given node x. If node x is not present then print "No Path". Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 x = 5Output : 1-&gt;2-&gt;5 Approach: Create a recursive function that traverses the different path in the binary tr
15 min read
Find all root to leaf path sum of a Binary Tree
Given a Binary Tree, the task is to print all the root to leaf path sum of the given Binary Tree. Examples: Input: 30 / \ 10 50 / \ / \ 3 16 40 60 Output: 43 56 120 140 Explanation: In the above binary tree there are 4 leaf nodes. Hence, total 4 path sum are present from root node to the leaf node. (i.e., 30-10-3, 30-10-16, 30-50-40, 30-50-60) Ther
8 min read
Print the path common to the two paths from the root to the two given nodes
Given a binary tree with distinct nodes(no two nodes have the same data values). The problem is to print the path common to the two paths from the root to the two given nodes n1 and n2. If either of the nodes are not present then print "No Common Path". Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 n1 = 4, n2 = 8 Output : 1-&gt;2 Path form ro
22 min read
Print common nodes on path from root (or common ancestors)
Given a binary tree and two nodes, the task is to Print all the nodes that are common for 2 given nodes in a binary tree. Examples: Given binary tree is : 1 / \ 2 3 / \ / \ 4 5 6 7 / / \ 8 9 10 Given nodes 9 and 7, so the common nodes are:- 1, 3 Asked in : Amazon Find the LCA of given two nodes.Print all ancestors of the LCA as done in this post, a
11 min read