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

📅  最后修改于: 2021-04-26 17:46:59             🧑  作者: 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


输出:
// 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)