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
  • Natural Numbers
  • Whole Numbers
  • Real Numbers
  • Integers
  • Rational Numbers
  • Irrational Numbers
  • Complex Numbers
  • Prime Numbers
  • Odd Numbers
  • Even Numbers
  • Properties of Numbers
  • Number System
Open In App
Next Article:
Print path from root to all nodes in a Complete Binary Tree
Next article icon

Print path from a node to root of given Complete Binary Tree

Last Updated : 11 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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       ................    /    \ ............  N - 1  N ............

Examples:

Input: N = 7
Output: 7 3 1
Explanation: The path from the node 7 to root is 7 -> 3 -> 1.

Input: N = 11
Output: 11 5 2 1
Explanation: The path from node 11 to root is 11 -> 5 -> 2 -> 1.

Naive Approach: The simplest approach to solve the problem is to perform DFS from the given node until the root node is encountered and print the path.

Time Complexity: O(N)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized based on the structure of the given Binary Tree. It can be observed that for every N, its parent node will be N / 2. Therefore, repeatedly print the current value of N and update N to N / 2 until N is equal to 1, i.e. root node is reached. 

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <iostream>
using namespace std;
 
// Function to print the path
// from node to root
void path_to_root(int node)
{
    // Iterate until root is reached
    while (node >= 1) {
 
        // Print the value of
        // the current node
        cout << node << ' ';
 
        // Move to parent of
        // the current node
        node /= 2;
    }
}
 
// Driver Code
int main()
{
    int N = 7;
    path_to_root(N);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
  
class GFG{
 
// Function to print the path
// from node to root
static void path_to_root(int node)
{
     
    // Iterate until root is reached
    while (node >= 1)
    {
         
        // Print the value of
        // the current node
        System.out.print(node + " ");
 
        // Move to parent of
        // the current node
        node /= 2;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 7;
     
    path_to_root(N);
}
}
 
// This code is contributed by shivanisinghss2110
 
 

Python3




# Python3 program for the above approach
 
# Function to print the path
# from node to root
def path_to_root(node):
     
    # Iterate until root is reached
    while (node >= 1):
 
        # Print the value of
        # the current node
        print(node, end = " ")
 
        # Move to parent of
        # the current node
        node //= 2
 
# Driver Code
if __name__ == '__main__':
 
    N = 7
 
    path_to_root(N)
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program for the above approach
using System;
class GFG
{
 
// Function to print the path
// from node to root
static void path_to_root(int node)
{
     
    // Iterate until root is reached
    while (node >= 1)
    {
         
        // Print the value of
        // the current node
        Console.Write(node + " ");
 
        // Move to parent of
        // the current node
        node /= 2;
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 7;   
    path_to_root(N);
}
}
 
// This code is contributed by shivanisinghss2110
 
 

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to print the path
// from node to root
function path_to_root(node)
{
     
    // Iterate until root is reached
    while (node >= 1)
    {
         
        // Print the value of
        // the current node
        document.write(node + " ");
 
        // Move to parent of
        // the current node
        node = parseInt(node / 2, 10);
    }
}
 
// Driver code
let N = 7;
 
path_to_root(N);
 
// This code is contributed by divyeshrabadiya07
 
</script>
 
 
Output: 
7 3 1

 

Time Complexity: O(log2(N))
Auxiliary Space: O(1)



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

N

nk14646
Improve
Article Tags :
  • DSA
  • Greedy
  • Mathematical
  • Tree
  • DFS
  • interview-preparation
  • Numbers
Practice Tags :
  • DFS
  • Greedy
  • Mathematical
  • Numbers
  • Tree

Similar Reads

  • Print path from root to all nodes in a Complete Binary Tree
    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
    9 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
  • Queries to calculate sum of the path from root to a given node in given Binary Tree
    Given an infinite complete binary tree rooted at node 1, where every ith node has two children, with values 2 * i and 2 * (i + 1). Given another array arr[] consisting of N positive integers, the task for each array element arr[i] is to find the sum of the node values that occur in a path from the r
    10 min read
  • Path from the root node to a given node in an N-ary Tree
    Given an integer N and an N-ary Tree of the following form: Every node is numbered sequentially, starting from 1, till the last level, which contains the node N.The nodes at every odd level contains 2 children and nodes at every even level contains 4 children. The task is to print the path from the
    10 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
  • Find the parent of a node in the given binary tree
    Given a Binary Tree and a node, the task is to find the parent of the given node in the tree. Return -1 if the given node is the root node.Note: In a binary tree, a parent node of a given node is the node that is directly connected above the given node. Examples: Input: target = 3 Output: 1Explanati
    6 min read
  • Find distance from root to given node in a binary tree
    Given the root of a binary tree and a key x in it, find the distance of the given key from the root. Dis­tance means the num­ber of edges between two nodes. Examples: Input: x = 45 Output: 3 Explanation: There are three edges on path from root to 45.For more understanding of question, in above tree
    11 min read
  • Count of root to leaf paths in a Binary Tree that form an AP
    Given a Binary Tree, the task is to count all paths from root to leaf which forms an Arithmetic Progression. Examples: Input: Output: 2 Explanation: The paths that form an AP in the given tree from root to leaf are: 1->3->5 (A.P. with common difference 2)1->6->11 (A.P. with common differ
    7 min read
  • Print cousins of a given node in Binary Tree
    Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.Example: Input : root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 and pointer to a node say 5. Output : 6, 7 The idea to first find level of given node using the approach discussed here. Once we hav
    15+ 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