原文:

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

  • binary tree is a up to [t2】 n t7 node level.
  • the node numbers are 1 to n , and 1 from the root.
  • the structure of the tree is as follows:

1 / \ 2 3 / \ / \ 4 5 6 7 ................ / \ ............ n - 1 n ............

示例:

输入: n = 7 输出: 7 3 1 解释:从节点 7 到根的路径是 7 - > 3 - > 1。

输入: n = 11 输出: 11 5 2 1 说明:从节点 11 到根的路径是 11 - > 5 - > 2 - > 1。

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

时间复杂度: o(n) 辅助空间: o(1)

高效方法:上述方法可以基于给定二叉树的结构进行优化。可以观察到,每个 n 的父节点都是 n / 2 。因此,重复打印 n 的当前值,并将 n 更新为 n / 2 ,直到 n 等于 1 ,即到达根节点。

下面是上述方法的实现:

c

// 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;
}

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

python 3

# 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

java 描述语言


output: 

7 3 1

时间复杂度:o(log2(n)) 辅助空间: o(1)