📌  相关文章
📜  查询以计算给定二叉树中从根到给定节点的路径之和

📅  最后修改于: 2021-04-17 15:23:13             🧑  作者: Mango

给定一个无限大的完整二叉树,其根源于节点1 ,其中每个i节点都有两个子节点,其值分别为2 * i2 *(i +1) 。给定另一个由N个正整数组成的数组arr [] ,每个数组元素arr [i]的任务是找到在从根节点到节点arr [i]的路径中出现的节点值之和。

例子:

天真的方法:最简单的方法是对每个数组元素arr [i]执行DFS遍历,以找到其从当前节点到根的路径,并打印该路径中节点值的总和。
时间复杂度: O(N * H),其中H是树的最大高度。
辅助空间: O(H)

高效方法:还可以基于观察到值N的节点的父级包含值N / 2来优化上述方法。请按照以下步骤解决问题:

  • 初始化一个变量,例如sumOfNode ,以将路径中的节点总数存储起来。
  • 遍历数组arr [i]并执行以下步骤:
    • 对于每个元素arr [i] ,将sumOfNode的值更新为sumOfNode + X,并将arr [i]更新为arr [i] / 2
    • arr [i]大于0时,重复上述步骤。
    • 打印sumOfNode的值作为每个数组元素arr [i]的结果

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
#include 
using namespace std;
 
// Function to find the sum of the
// path from root to the current node
void sumOfNodeInAPath(int node_value)
{
    // Sum of nodes in the path
    int sum_of_node = 0;
 
    // Iterate until root is reached
    while (node_value) {
 
        sum_of_node += node_value;
 
        // Update the node value
        node_value /= 2;
    }
 
    // Print the resultant sum
    cout << sum_of_node;
 
    return;
}
 
// Function to print the path
// sum for each query
void findSum(vector Q)
{
    // Traverse the queries
    for (int i = 0; i < Q.size(); i++) {
 
        int node_value = Q[i];
 
        sumOfNodeInAPath(node_value);
 
        cout << " ";
    }
}
 
// Driver Code
int main()
{
    vector arr = { 1, 5, 20, 100 };
    findSum(arr);
 
    return 0;
}


Java
/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.ArrayList;
class GFG {
 
  // Function to find the sum of the
  // path from root to the current node
  public static void sumOfNodeInAPath(int node_value)
  {
    // Sum of nodes in the path
    int sum_of_node = 0;
 
    // Iterate until root is reached
    while (node_value > 0) {
 
      sum_of_node += node_value;
 
      // Update the node value
      node_value /= 2;
    }
 
    // Print the resultant sum
    System.out.print(sum_of_node);
  }
 
  // Function to print the path
  // sum for each query
  public static void findSum(ArrayList Q)
  {
    // Traverse the queries
    for (int i = 0; i < Q.size(); i++) {
 
      int node_value = Q.get(i);
 
      sumOfNodeInAPath(node_value);
 
      System.out.print(" ");
    }
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    // arraylist to store integers
    ArrayList arr = new ArrayList<>();
    arr.add(1);
    arr.add(5);
    arr.add(20);
    arr.add(100);
    findSum(arr);
  }
}
 
// This code is contributed by aditya7409.


Python3
# Python program for the above approach
 
# Function to find the sum of the
# path from root to the current node
def sumOfNodeInAPath(node_value):
     
    # Sum of nodes in the path
    sum_of_node = 0
     
    # Iterate until root is reached
    while (node_value):
         
        sum_of_node += node_value
         
        # Update the node value
        node_value //= 2
         
    # Prthe resultant sum
    print(sum_of_node, end = " ")
     
# Function to prthe path
# sum for each query
def findSum(Q):
     
    # Traverse the queries
    for i in range(len(Q)):
        node_value = Q[i]
        sumOfNodeInAPath(node_value)
        print(end = "")
 
# Driver Code
arr = [1, 5, 20, 100]
findSum(arr)
 
# This code is contributed by shubhamsingh10


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
  // Function to find the sum of the
  // path from root to the current node
  public static void sumOfNodeInAPath(int node_value)
  {
     
    // Sum of nodes in the path
    int sum_of_node = 0;
 
    // Iterate until root is reached
    while (node_value > 0) {
 
      sum_of_node += node_value;
 
      // Update the node value
      node_value /= 2;
    }
 
    // Print the resultant sum
    Console.Write(sum_of_node);
  }
 
  // Function to print the path
  // sum for each query
  public static void findSum(List Q)
  {
    // Traverse the queries
    for (int i = 0; i < Q.Count ; i++) {
 
      int node_value = Q[i];
      sumOfNodeInAPath(node_value);
      Console.Write(" ");
    }
  }
 
// Driver Code
static public void Main()
{
   
    // arraylist to store integers
    List arr = new List();
    arr.Add(1);
    arr.Add(5);
    arr.Add(20);
    arr.Add(100);
    findSum(arr);
}
}
// This code is contributed by sanjoy_62.


输出:
1 8 38 197

时间复杂度: O(N * log X),其中X数组的最大元素
辅助空间: O(1)