📌  相关文章
📜  与 BST 中给定节点距离 K 处具有较小值的所有节点的总和

📅  最后修改于: 2022-05-13 01:56:05.102000             🧑  作者: Mango

与 BST 中给定节点距离 K 处具有较小值的所有节点的总和

给定二叉搜索树、BST 中的目标节点和整数值K ,任务是找到距离目标节点K且值小于目标节点的所有节点的总和。

例子:

方法:给定的问题可以通过在目标节点下方执行K距离的 DFS 遍历和从目标节点向上执行K距离的 DFS 遍历来解决。请按照以下步骤解决问题:

  • 定义一个函数kDistanceDownSum(root, k, &sum)并执行以下步骤:
    • 对于基本情况,检查是否为nullptrk是否小于0 ,然后从函数返回。
    • 如果k的值等于0 ,则将root->val添加到变量sum并返回。
    • 为左右子树调用相同的函数kDistanceDownSum(root->left, k-1, sum)kDistanceDownSum(root->right, k – 1, sum)
  • 对于基本情况,检查是否为nullptr ,然后返回-1
  • 如果目标相同,则调用函数kDistanceDownSum(root->left, k – 1, sum)计算第一类节点的总和并返回0 (不可能有第二类节点)。
  • 将变量dl初始化为-1 ,如果目标小于 root,则将dl的值设置为函数kDistanceSum(root->left, target k, sum)的返回值。
  • 如果dl的值不等于-1 ,那么如果sum等于(dl + 1) ,则将root->data的值加到sum中,然后返回-1
  • 同样,将变量dr初始化为-1 ,如果target大于root ,则将dr的值更新为kDistanceSum(root->right, target k, sum)返回的值。
  • 如果dr的值不等于-1 ,那么如果sum的值等于(dr + 1) ,则将root->data的值添加到sum 。否则,调用函数kDistanceDownSum(root->left, k – dr – 2, sum)并返回(1 + dr)
  • 执行上述步骤后,打印ans的值作为结果总和。

以下是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Structure of Tree
struct TreeNode {
 
    int data;
    TreeNode* left;
    TreeNode* right;
 
    // Constructor
    TreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};
 
// Function to add the node to the sum
// below the target node
void kDistanceDownSum(TreeNode* root,
                      int k, int& sum)
{
 
    // Base Case
    if (root == NULL || k < 0)
        return;
 
    // If Kth distant node is reached
    if (k == 0) {
        sum += root->data;
        return;
    }
 
    // Recur for the left and the
    // right subtrees
    kDistanceDownSum(root->left,
                     k - 1, sum);
    kDistanceDownSum(root->right,
                     k - 1, sum);
}
 
// Function to find the K distant nodes
// from target node, it returns -1 if
// target node is not present in tree
int kDistanceSum(TreeNode* root,
                 int target,
                 int k, int& sum)
{
    // Base Case 1
    if (root == NULL)
        return -1;
 
    // If target is same as root.
    if (root->data == target) {
        kDistanceDownSum(root->left,
                         k - 1, sum);
        return 0;
    }
 
    // Recurr for the left subtree
    int dl = -1;
 
    // Tree is BST so reduce the
    // search space
    if (target < root->data) {
        dl = kDistanceSum(root->left,
                          target, k, sum);
    }
 
    // Check if target node was found
    // in left subtree
    if (dl != -1) {
 
        // If root is at distance k from
        // the target
        if (dl + 1 == k)
            sum += root->data;
 
        // Node less than target will be
        // present in left
        return -1;
    }
 
    // When node is not present in the
    // left subtree
    int dr = -1;
    if (target > root->data) {
        dr = kDistanceSum(root->right,
                          target, k, sum);
    }
 
    if (dr != -1) {
 
        // If Kth distant node is reached
        if (dr + 1 == k)
            sum += root->data;
 
        // Node less than target at k
        // distance maybe present in the
        // left tree
        else
            kDistanceDownSum(root->left,
                             k - dr - 2, sum);
 
        return 1 + dr;
    }
 
    // If target was not present in the
    // left nor in right subtree
    return -1;
}
 
// Function to insert a node in BST
TreeNode* insertNode(int data,
                     TreeNode* root)
{
    // If root is NULL
    if (root == NULL) {
        TreeNode* node = new TreeNode(data);
        return node;
    }
 
    // Insert the data in right half
    else if (data > root->data) {
        root->right = insertNode(
            data, root->right);
    }
 
    // Insert the data in left half
    else if (data <= root->data) {
        root->left = insertNode(
            data, root->left);
    }
 
    // Return the root node
    return root;
}
 
// Function to find the sum of K distant
// nodes from the target node having
// value less than target node
void findSum(TreeNode* root, int target,
             int K)
{
 
    // Stores the sum of nodes having
    // values < target at K distance
    int sum = 0;
 
    kDistanceSum(root, target, K, sum);
 
    // Print the resultant sum
    cout << sum;
}
 
// Driver Code
int main()
{
    TreeNode* root = NULL;
    int N = 11;
    int tree[] = { 3, 1, 7, 0, 2, 5,
                   10, 4, 6, 9, 8 };
 
    // Create the Tree
    for (int i = 0; i < N; i++) {
        root = insertNode(tree[i], root);
    }
 
    int target = 7;
    int K = 2;
    findSum(root, target, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
public class GFG{
    static int sum;
   
// Structure of Tree
static class TreeNode {
 
    int data;
    TreeNode left;
    TreeNode right;
 
    // Constructor
    TreeNode(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
};
 
// Function to add the node to the sum
// below the target node
static void kDistanceDownSum(TreeNode root,
                      int k)
{
 
    // Base Case
    if (root == null || k < 0)
        return;
 
    // If Kth distant node is reached
    if (k == 0) {
        sum += root.data;
        return;
    }
 
    // Recur for the left and the
    // right subtrees
    kDistanceDownSum(root.left,
                     k - 1);
    kDistanceDownSum(root.right,
                     k - 1);
}
 
// Function to find the K distant nodes
// from target node, it returns -1 if
// target node is not present in tree
static int kDistanceSum(TreeNode root,
                 int target,
                 int k)
{
    // Base Case 1
    if (root == null)
        return -1;
 
    // If target is same as root.
    if (root.data == target) {
        kDistanceDownSum(root.left,
                         k - 1);
    return 0;
    }
 
    // Recurr for the left subtree
    int dl = -1;
 
    // Tree is BST so reduce the
    // search space
    if (target < root.data) {
        dl = kDistanceSum(root.left,
                          target, k);
    }
 
    // Check if target node was found
    // in left subtree
    if (dl != -1) {
 
        // If root is at distance k from
        // the target
        if (dl + 1 == k)
            sum += root.data;
 
        // Node less than target will be
        // present in left
        return -1;
    }
 
    // When node is not present in the
    // left subtree
    int dr = -1;
    if (target > root.data) {
        dr = kDistanceSum(root.right,
                          target, k);
    }
 
    if (dr != -1) {
 
        // If Kth distant node is reached
        if (dr + 1 == k)
            sum += root.data;
 
        // Node less than target at k
        // distance maybe present in the
        // left tree
        else
            kDistanceDownSum(root.left,
                             k - dr - 2);
 
        return 1 + dr;
    }
 
    // If target was not present in the
    // left nor in right subtree
    return -1;
}
 
// Function to insert a node in BST
static TreeNode insertNode(int data,
                     TreeNode root)
{
    // If root is null
    if (root == null) {
        TreeNode node = new TreeNode(data);
        return node;
    }
 
    // Insert the data in right half
    else if (data > root.data) {
        root.right = insertNode(
            data, root.right);
    }
 
    // Insert the data in left half
    else if (data <= root.data) {
        root.left = insertNode(
            data, root.left);
    }
 
    // Return the root node
    return root;
}
 
// Function to find the sum of K distant
// nodes from the target node having
// value less than target node
static void findSum(TreeNode root, int target,
             int K)
{
 
    // Stores the sum of nodes having
    // values < target at K distance
    sum = 0;
 
    kDistanceSum(root, target, K);
 
    // Print the resultant sum
    System.out.print(sum);
}
 
// Driver Code
public static void main(String[] args)
{
    TreeNode root = null;
    int N = 11;
    int tree[] = { 3, 1, 7, 0, 2, 5,
                   10, 4, 6, 9, 8 };
 
    // Create the Tree
    for (int i = 0; i < N; i++) {
        root = insertNode(tree[i], root);
    }
 
    int target = 7;
    int K = 2;
    findSum(root, target, K);
 
}
}
 
// This code is contributed by 29AjayKumar


Python3
# python 3 program for the above approach
 
# Structure of Tree
sum = 0
 
class Node:
    # A constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to add the node to the sum
# below the target node
def kDistanceDownSum(root, k):
    global sum
    # Base Case
    if (root == None or k < 0):
        return
 
    # If Kth distant node is reached
    if (k == 0):
        sum += root.data
        return
 
    # Recur for the left and the
    # right subtrees
    kDistanceDownSum(root.left,k - 1)
    kDistanceDownSum(root.right,k - 1)
 
# Function to find the K distant nodes
# from target node, it returns -1 if
# target node is not present in tree
def kDistanceSum(root, target, k):
    global sum
    # Base Case 1
    if (root == None):
        return -1
 
    # If target is same as root.
    if (root.data == target):
        kDistanceDownSum(root.left,k - 1)
        return 0
 
    # Recurr for the left subtree
    dl = -1
 
    # Tree is BST so reduce the
    # search space
    if (target < root.data):
        dl = kDistanceSum(root.left, target, k)
 
    # Check if target node was found
    # in left subtree
    if (dl != -1):
        # If root is at distance k from
        # the target
        if (dl + 1 == k):
            sum += root.data
 
        # Node less than target will be
        # present in left
        return -1
 
    # When node is not present in the
    # left subtree
    dr = -1
    if (target > root.data):
        dr = kDistanceSum(root.right, target, k)
 
    if (dr != -1):
        # If Kth distant node is reached
        if (dr + 1 == k):
            sum += root.data
 
        # Node less than target at k
        # distance maybe present in the
        # left tree
        else:
            kDistanceDownSum(root.left, k - dr - 2)
 
        return 1 + dr
 
    # If target was not present in the
    # left nor in right subtree
    return -1
 
# Function to insert a node in BST
def insertNode(data, root):
    # If root is NULL
    if (root == None):
        node = Node(data)
        return node
 
    # Insert the data in right half
    elif (data > root.data):
        root.right = insertNode(data, root.right)
 
    # Insert the data in left half
    elif(data <= root.data):
        root.left = insertNode(data, root.left)
 
    # Return the root node
    return root
 
# Function to find the sum of K distant
# nodes from the target node having
# value less than target node
def findSum(root, target, K):
   
    # Stores the sum of nodes having
    # values < target at K distance
    kDistanceSum(root, target, K)
 
    # Print the resultant sum
    print(sum)
 
# Driver Code
if __name__ == '__main__':
    root = None
    N = 11
    tree = [3, 1, 7, 0, 2, 5,10, 4, 6, 9, 8]
 
    # Create the Tree
    for i in range(N):
        root = insertNode(tree[i], root)
 
    target = 7
    K = 2
    findSum(root, target, K)
     
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C# program for the above approach
using System;
 
public class GFG{
    static int sum;
   
// Structure of Tree
public
 
 class TreeNode {
 
    public
 
 int data;
    public
 
 TreeNode left;
    public
 
 TreeNode right;
 
    // Constructor
    public TreeNode(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
};
 
// Function to add the node to the sum
// below the target node
static void kDistanceDownSum(TreeNode root,
                      int k)
{
 
    // Base Case
    if (root == null || k < 0)
        return;
 
    // If Kth distant node is reached
    if (k == 0) {
        sum += root.data;
        return;
    }
 
    // Recur for the left and the
    // right subtrees
    kDistanceDownSum(root.left,
                     k - 1);
    kDistanceDownSum(root.right,
                     k - 1);
}
 
// Function to find the K distant nodes
// from target node, it returns -1 if
// target node is not present in tree
static int kDistanceSum(TreeNode root,
                 int target,
                 int k)
{
    // Base Case 1
    if (root == null)
        return -1;
 
    // If target is same as root.
    if (root.data == target) {
        kDistanceDownSum(root.left,
                         k - 1);
    return 0;
    }
 
    // Recurr for the left subtree
    int dl = -1;
 
    // Tree is BST so reduce the
    // search space
    if (target < root.data) {
        dl = kDistanceSum(root.left,
                          target, k);
    }
 
    // Check if target node was found
    // in left subtree
    if (dl != -1) {
 
        // If root is at distance k from
        // the target
        if (dl + 1 == k)
            sum += root.data;
 
        // Node less than target will be
        // present in left
        return -1;
    }
 
    // When node is not present in the
    // left subtree
    int dr = -1;
    if (target > root.data) {
        dr = kDistanceSum(root.right,
                          target, k);
    }
 
    if (dr != -1) {
 
        // If Kth distant node is reached
        if (dr + 1 == k)
            sum += root.data;
 
        // Node less than target at k
        // distance maybe present in the
        // left tree
        else
            kDistanceDownSum(root.left,
                             k - dr - 2);
 
        return 1 + dr;
    }
 
    // If target was not present in the
    // left nor in right subtree
    return -1;
}
 
// Function to insert a node in BST
static TreeNode insertNode(int data,
                     TreeNode root)
{
    // If root is null
    if (root == null) {
        TreeNode node = new TreeNode(data);
        return node;
    }
 
    // Insert the data in right half
    else if (data > root.data) {
        root.right = insertNode(
            data, root.right);
    }
 
    // Insert the data in left half
    else if (data <= root.data) {
        root.left = insertNode(
            data, root.left);
    }
 
    // Return the root node
    return root;
}
 
// Function to find the sum of K distant
// nodes from the target node having
// value less than target node
static void findSum(TreeNode root, int target,
             int K)
{
 
    // Stores the sum of nodes having
    // values < target at K distance
    sum = 0;
 
    kDistanceSum(root, target, K);
 
    // Print the resultant sum
    Console.Write(sum);
}
 
// Driver Code
public static void Main(String[] args)
{
    TreeNode root = null;
    int N = 11;
    int []tree = { 3, 1, 7, 0, 2, 5,
                   10, 4, 6, 9, 8 };
 
    // Create the Tree
    for (int i = 0; i < N; i++) {
        root = insertNode(tree[i], root);
    }
 
    int target = 7;
    int K = 2;
    findSum(root, target, K);
 
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出:
11

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