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

📅  最后修改于: 2021-09-04 11:38:58             🧑  作者: Mango

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

例子:

朴素方法:最简单的方法是对每个数组元素arr[i]执行DFS Traversal以找到其从当前节点到根的路径,并打印该路径中节点值的总和。
时间复杂度: 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
         
    # Print the resultant sum
    print(sum_of_node, end = " ")
     
# Function to print the 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.


Javascript


输出:
1 8 38 197

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live