给定整数N ,任务是查找从第N个节点到二进制树根的路径,其形式如下:
- 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:
例子:
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.
天真的方法:解决问题的最简单方法是执行DFS 从给定节点直到遇到根节点,然后打印路径。
时间复杂度: O(N)
辅助空间: O(1)
高效方法:可以根据给定二叉树的结构来优化上述方法。可以观察到,每隔N个节点,其父节点将为N / 2 。因此,反复打印的N和更新N到N / 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)