📌  相关文章
📜  根到叶的路径总和等于BST中的给定数字

📅  最后修改于: 2021-05-24 23:15:10             🧑  作者: Mango

给定一个BST和一个数字。任务是检查给定的数字是否等于给定的Binary Search Tree中从根叶子到任何根到叶路径的所有根节点的总和。

方法:想法是以自上而下的方式从根遍历到所有叶子,并维护一个path []数组以存储当前的根到叶子的路径。遍历时,将当前路径的所有节点的数据存储在数组path []中。每当到达叶节点时,就使用数组path []计算当前路径上所有节点的总和,并检查它是否等于给定的总和。

下面是上述方法的实现:

C++
// CPP program to check if root to leaf path
// sum to a given number in BST
  
#include
using namespace std;
  
// BST node
struct Node { 
    int data; 
    Node *left, *right; 
};
  
/* Helper function that allocates a new node */
Node* newNode(int data) 
{ 
    Node* node = (Node*)malloc(sizeof(Node)); 
    node->data = data; 
    node->left = node->right = NULL; 
    return (node); 
} 
  
// Function to check if root to leaf path
// sum to a given number in BST
int checkThesum(struct Node *root, int path[], int i, int sum)
{
    int sum1 = 0, x, y, j;
      
    if(root == NULL)
        return 0;
          
    // insert the data of a node
    path[i] = root->data;
      
    // if the node is leaf
    // add all the element in array
    if(root->left==NULL&&root->right==NULL)
    {
        for(j = 0; j <= i; j++)
            sum1 = sum1 + path[j];
              
        // if the sum of root node to leaf 
        // node data is equal then return 1
        if(sum == sum1)
            return 1;
        else
            return 0;
    }
  
    x = checkThesum(root->left, path, i+1, sum);
      
    // if x is 1, it means the given sum is matched 
    // with root to leaf node sum
    if(x==1) 
        return 1;
    else
    {
        return checkThesum(root->right, path, i+1, sum);
    }
}
  
// Driver code
int main()
{
    int path[100], sum = 164;
      
    Node *root = newNode(45);
    root->left = newNode(38);
    root->left->left = newNode(33);
    root->left->left->left = newNode(31);
    root->left->left->right = newNode(35);
    root->left->right = newNode(41);
    root->left->right->left = newNode(40);
    root->left->right->right = newNode(44);
    root->right = newNode(50);
    root->right->left = newNode(47);
    root->right->left->left = newNode(46);
    root->right->left->right = newNode(48);
    root->right->right = newNode(52);
    root->right->right->left = newNode(51);
    root->right->right->right = newNode(55);
      
    if(checkThesum(root, path, 0, sum)==1)
        cout<<"YES\n";
    else
        cout<<"NO\n";
          
    return 0;
}


Java
// Java program to check if 
// root to leaf path sum to
// a given number in BST
class GFG
{
      
// BST node
static class Node 
{ 
    int data; 
    Node left, right; 
}
  
/* Helper function that 
   allocates a new node */
static Node newNode(int data) 
{ 
    Node node = new Node(); 
    node.data = data; 
    node.left = node.right = null; 
    return (node); 
} 
  
// Function to check if root 
// to leaf path sum to a
// given number in BST
static int checkThesum(Node root, int path[],
                           int i, int sum)
{
    int sum1 = 0, x, y, j;
      
    if(root == null)
        return 0;
          
    // insert the data of a node
    path[i] = root.data;
      
    // if the node is leaf
    // add all the element in array
    if(root.left == null && 
       root.right == null)
    {
        for(j = 0; j <= i; j++)
            sum1 = sum1 + path[j];
              
        // if the sum of root node to leaf 
        // node data is equal then return 1
        if(sum == sum1)
            return 1;
        else
            return 0;
    }
  
    x = checkThesum(root.left, path, 
                        i + 1, sum);
      
    // if x is 1, it means the 
    // given sum is matched with 
    // root to leaf node sum
    if(x == 1) 
        return 1;
    else
    {
        return checkThesum(root.right, path,
                                i + 1, sum);
    }
}
  
// Driver code
public static void main(String args[])
{
    int path[] = new int[100], sum = 164;
      
    Node root = newNode(45);
    root.left = newNode(38);
    root.left.left = newNode(33);
    root.left.left.left = newNode(31);
    root.left.left.right = newNode(35);
    root.left.right = newNode(41);
    root.left.right.left = newNode(40);
    root.left.right.right = newNode(44);
    root.right = newNode(50);
    root.right.left = newNode(47);
    root.right.left.left = newNode(46);
    root.right.left.right = newNode(48);
    root.right.right = newNode(52);
    root.right.right.left = newNode(51);
    root.right.right.right = newNode(55);
      
    if(checkThesum(root, path, 0, sum) == 1)
        System.out.print("YES\n");
    else
        System.out.print("NO\n");
} 
}
  
// This code is contributed by Arnab Kundu


Python3
# Python program to check if root to leaf path
# sum to a given number in BST
import math
  
# BST node
class Node: 
    def __init__(self,data): 
        self.data = data 
        self.left = None
        self.right= None
  
# Helper function that allocates a new node */
def newNode(data): 
    node = Node(data) 
    node.data = data 
    node.left = None
    node.right = None
  
    return node 
  
# Function to check if root to leaf path
# sum to a given number in BST
def checkThesum(root, path, i, sum):
    sum1 = 0
      
    # x, y, j 
    if(root == None):
        return 0
          
    # insert the data of a node
    path[i] = root.data
      
    # if the node is leaf
    # add all the element in array
    if(root.left == None and root.right == None):
        for j in range(0, i + 1):
            sum1 = sum1 + path[j]
              
        # if the sum of root node to leaf 
        # node data is equal then return 1
        if(sum == sum1):
            return 1
        else:
            return 0
      
    x = checkThesum(root.left, path, i + 1, sum)
      
    # if x is 1, it means the given sum is matched 
    # with root to leaf node sum
    if(x == 1):
        return 1
    else:
        return checkThesum(root.right, path, i + 1, sum)
      
# Driver code
if __name__=='__main__': 
  
    path = [None] * 100
    sum = 164
      
    root = newNode(45)
    root.left = newNode(38)
    root.left.left = newNode(33)
    root.left.left.left = newNode(31)
    root.left.left.right = newNode(35)
    root.left.right = newNode(41)
    root.left.right.left = newNode(40)
    root.left.right.right = newNode(44)
    root.right = newNode(50)
    root.right.left = newNode(47)
    root.right.left.left = newNode(46)
    root.right.left.right = newNode(48)
    root.right.right = newNode(52)
    root.right.right.left = newNode(51)
    root.right.right.right = newNode(55)
      
    if(checkThesum(root, path, 0, sum) == 1):
        print("YES")
    else:
        print("NO")
          
# This code is contributed by Srathore


C#
// C# program to check if 
// root to leaf path sum to 
// a given number in BST 
using System;
  
class GFG 
{ 
      
// BST node 
public class Node 
{ 
    public int data; 
    public Node left, right; 
} 
  
/* Helper function that 
allocates a new node */
static Node newNode(int data) 
{ 
    Node node = new Node(); 
    node.data = data; 
    node.left = node.right = null; 
    return (node); 
} 
  
// Function to check if root 
// to leaf path sum to a 
// given number in BST 
static int checkThesum(Node root, int []path, 
                        int i, int sum) 
{ 
    int sum1 = 0, x, y, j; 
      
    if(root == null) 
        return 0; 
          
    // insert the data of a node 
    path[i] = root.data; 
      
    // if the node is leaf 
    // add all the element in array 
    if(root.left == null && 
    root.right == null) 
    { 
        for(j = 0; j <= i; j++) 
            sum1 = sum1 + path[j]; 
              
        // if the sum of root node to leaf 
        // node data is equal then return 1 
        if(sum == sum1) 
            return 1; 
        else
            return 0; 
    } 
  
    x = checkThesum(root.left, path, 
                        i + 1, sum); 
      
    // if x is 1, it means the 
    // given sum is matched with 
    // root to leaf node sum 
    if(x == 1) 
        return 1; 
    else
    { 
        return checkThesum(root.right, path, 
                                i + 1, sum); 
    } 
} 
  
// Driver code 
public static void Main(String []args) 
{ 
    int []path = new int[100];int sum = 164; 
      
    Node root = newNode(45); 
    root.left = newNode(38); 
    root.left.left = newNode(33); 
    root.left.left.left = newNode(31); 
    root.left.left.right = newNode(35); 
    root.left.right = newNode(41); 
    root.left.right.left = newNode(40); 
    root.left.right.right = newNode(44); 
    root.right = newNode(50); 
    root.right.left = newNode(47); 
    root.right.left.left = newNode(46); 
    root.right.left.right = newNode(48); 
    root.right.right = newNode(52); 
    root.right.right.left = newNode(51); 
    root.right.right.right = newNode(55); 
      
    if(checkThesum(root, path, 0, sum) == 1) 
        Console.Write("YES\n"); 
    else
        Console.Write("NO\n"); 
} 
} 
  
// This code is contributed 29AjayKumar


输出:
YES