📜  打印从节点到给定完全二叉树的根的路径

📅  最后修改于: 2021-10-26 02:37:08             🧑  作者: Mango

给定一个整数N ,任务是找到从第N节点到以下形式的二叉树根的路径:

例子:

朴素的方法:解决问题的最简单的方法是执行DFS 从给定节点直到遇到根节点并打印路径。

时间复杂度: O(N)
辅助空间: O(1)

高效的方法:可以根据给定的二叉树的结构优化上述方法。可以观察到,对于每个N ,其父节点将是N / 2 。因此,反复打印的N和更新NN / 2的电流值,直到N等于1时,达到即根节点。

下面是上述方法的实现:

C++
1
           /       \
          2         3
       /    \    /   \
      4     5    6    7
      ................
   /    \ ............
 N - 1  N ............


Java
// C++ program for the above approach
 
#include 
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;
}


Python3
// 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


C#
# 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


Javascript
// 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


输出:

时间复杂度: O(log 2 (N))
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程