Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Print Root-to-Leaf Paths in a Binary Tree
Next article icon

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

Last Updated : 10 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
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 [Tex]i     [/Tex]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.



Next Article
Print Root-to-Leaf Paths in a Binary Tree
author
devanshuagarwal
Improve
Article Tags :
  • Algorithms
  • Backtracking
  • C++
  • DSA
  • Recursion
  • Technical Scripter
  • Tree
Practice Tags :
  • CPP
  • Algorithms
  • Backtracking
  • Recursion
  • Tree

Similar Reads

  • 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
    4 min read
  • Print all leaf nodes of a binary tree from right to left
    Given a binary tree, the task is to print all the leaf nodes of the binary tree from right to left. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 7 6 5 4 Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 9 8 7 4 Recursive Approach: Traverse the tree in Preorder fashion, by first processing t
    14 min read
  • Print Root-to-Leaf Paths in a Binary Tree
    Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree. Example: Input: Output: 1 2 41 2 51 3 Using Recursion - O(n) Time and O(h) SpaceIn the recursive approach to print all paths from the root to leaf nodes, we can perfo
    2 min read
  • Sort the path from root to a given node in a Binary Tree
    Given a Binary tree, the task is to sort the particular path from to a given node of the binary tree. You are given a Key Node and Tree. The task is to sort the path till that particular node. Examples: Input : 3 / \ 4 5 / \ \ 1 2 6 key = 2 Output : 2 / \ 3 5 / \ \ 1 4 6 Inorder :- 1 3 4 2 5 6 Here
    6 min read
  • Count number of nodes in a complete Binary Tree
    Given the root of a Complete Binary Tree consisting of N nodes, the task is to find the total number of nodes in the given Binary Tree. Examples: Input: Output: 7 Input: Output: 5 Native Approach: The simple approach to solving the given tree is to perform the DFS Traversal on the given tree and cou
    15+ min read
  • Print all full nodes in a Binary Tree
    Given a binary tree, print all nodes will are full nodes. Full Nodes are nodes which has both left and right children as non-empty. Examples: Input : 10 / \ 8 2 / \ / 3 5 7 Output : 10 8 Input : 1 / \ 2 3 / \ 4 6 Output : 1 3 This is a simple problem. We do any of the tra­ver­sals (Inorder, Pre­orde
    4 min read
  • Print all internal nodes of a Binary tree
    Given a Binary tree, the task is to print all the internal nodes in a tree. An internal node is a node which carries at least one child or in other words, an internal node is not a leaf node. Here we intend to print all such internal nodes in level order. Consider the following Binary Tree: Input: O
    7 min read
  • Print all the paths from root, with a specified sum in Binary tree
    Given a Binary tree and a sum, the task is to return all the paths, starting from root, that sums upto the given sum.Note: This problem is different from root to leaf paths. Here path doesn't need to end on a leaf node. Examples: Input: Output: [[1, 3, 4]]Explanation: The below image shows the path
    8 min read
  • Print all the root-to-leaf paths of a Binary Tree whose XOR is non-zero
    Given a Binary Tree, the task is to print all root-to-leaf paths of this tree whose xor value is non-zero. Examples: Input: 10 / \ 10 3 / \ 10 3 / \ / \ 7 3 42 13 / 7 Output: 10 3 10 7 10 3 3 42 Explanation: All the paths in the given binary tree are : {10, 10} xor value of the path is = 10 ^ 10 = 0
    11 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 find the first smallest root to leaf path. We basically need to find the leftmost root to leaf path that has the minimum number of nodes. The root to leaf path in below image is 1-> 3 which is the leftmost root to leaf path that has the min
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences