📌  相关文章
📜  查找根中是否有一对叶子路径,其总和等于根的数据

📅  最后修改于: 2021-10-28 01:34:08             🧑  作者: Mango

给定一棵二叉树,找出根到叶路径是否存在一对,使得对中的值之和等于根的数据。例如,在下面的树中,任何根到叶路径中都没有总和等于根数据的对。

这个想法基于散列和树遍历。这个想法类似于数组对和问题的方法2。

  • 创建一个空的哈希表。
  • 以 Preorder 方式开始遍历树。
  • 如果到达叶节点,则返回 false。
  • 对于每个访问过的节点,检查根的数据减去当前节点的数据是否存在于哈希表中。如果是,则返回 true。否则在哈希表中插入当前节点。
  • 递归检查左子树和右子树。
  • 从哈希表中删除当前节点,使其不会出现在其他根到叶路径中。

下面是上述想法的实现。

C++
// C++ program to find if there is a pair in any root
// to leaf path with sum equals to root's key.
#include
using namespace std;
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node
{
    int data;
    struct Node* left, *right;
};
 
/* utility that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newnode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right  = NULL;
    return (node);
}
 
// Function to print root to leaf path which satisfies the condition
bool printPathUtil(Node *node, unordered_set &s, int root_data)
{
    // Base condition
    if (node == NULL)
        return false;
 
    // Check if current node makes a pair with any of the
    // existing elements in set.
    int rem = root_data - node->data;
    if (s.find(rem) != s.end())
        return true;
 
    // Insert current node in set
    s.insert(node->data);
 
    // If result returned by either left or right child is
    // true, return true.
    bool res = printPathUtil(node->left, s, root_data) ||
               printPathUtil(node->right, s, root_data);
 
    // Remove current node from hash table
    s.erase(node->data);
 
    return res;
}
 
// A wrapper over printPathUtil()
bool isPathSum(Node *root)
{
   // create an empty hash table
   unordered_set s;
 
   // Recursively check in left and right subtrees.
   return printPathUtil(root->left, s, root->data) ||
          printPathUtil(root->right, s, root->data);
}
 
// Driver program to run the case
int main()
{
    struct Node *root = newnode(8);
    root->left    = newnode(5);
    root->right   = newnode(4);
    root->left->left = newnode(9);
    root->left->right = newnode(7);
    root->left->right->left = newnode(1);
    root->left->right->right = newnode(12);
    root->left->right->right->right = newnode(2);
    root->right->right = newnode(11);
    root->right->right->left = newnode(3);
    isPathSum(root)? cout << "Yes" : cout << "No";
    return 0;
}


Java
// Java program to find if there is a pair in any root
// to leaf path with sum equals to root's key.
import java.util.*;
 
class GFG
{
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
static class Node
{
    int data;
    Node left, right;
};
 
/* utility that allocates a new node with the
given data and null left and right pointers. */
static Node newnode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
 
// Function to print root to leaf path which satisfies the condition
static boolean printPathUtil(Node node, HashSet s, int root_data)
{
    // Base condition
    if (node == null)
        return false;
 
    // Check if current node makes a pair with any of the
    // existing elements in set.
    int rem = root_data - node.data;
    if (s.contains(rem))
        return true;
 
    // Insert current node in set
    s.add(node.data);
 
    // If result returned by either left or right child is
    // true, return true.
    boolean res = printPathUtil(node.left, s, root_data) ||
            printPathUtil(node.right, s, root_data);
 
    // Remove current node from hash table
    s.remove(node.data);
 
    return res;
}
 
// A wrapper over printPathUtil()
static boolean isPathSum(Node root)
{
     
// create an empty hash table
HashSet s = new HashSet();
 
// Recursively check in left and right subtrees.
return printPathUtil(root.left, s, root.data) ||
        printPathUtil(root.right, s, root.data);
}
 
// Driver code
public static void main(String[] args)
{
    Node root = newnode(8);
    root.left = newnode(5);
    root.right = newnode(4);
    root.left.left = newnode(9);
    root.left.right = newnode(7);
    root.left.right.left = newnode(1);
    root.left.right.right = newnode(12);
    root.left.right.right.right = newnode(2);
    root.right.right = newnode(11);
    root.right.right.left = newnode(3);
    System.out.print(isPathSum(root)==true ?"Yes" : "No");
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to find if there is a
# pair in any root to leaf path with sum
# equals to root's key
 
# A binary tree node has data, pointer to
# left child and a pointer to right child
 
""" utility that allocates a new node with the
given data and None left and right pointers. """
class newnode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
         
# Function to prroot to leaf path which
# satisfies the condition
def printPathUtil(node, s, root_data) :
 
    # Base condition
    if (node == None) :
        return False
 
    # Check if current node makes a pair
    # with any of the existing elements in set.
    rem = root_data - node.data
    if rem in s:
        return True
 
    # Insert current node in set
    s.add(node.data)
 
    # If result returned by either left or
    # right child is True, return True.
    res = printPathUtil(node.left, s, root_data) or \
           printPathUtil(node.right, s, root_data)
 
    # Remove current node from hash table
    s.remove(node.data)
 
    return res
 
# A wrapper over printPathUtil()
def isPathSum(root) :
     
    # create an empty hash table
    s = set()
     
    # Recursively check in left and right subtrees.
    return printPathUtil(root.left, s, root.data) or \
           printPathUtil(root.right, s, root.data)
 
# Driver Code
if __name__ == '__main__':
    root = newnode(8)
    root.left = newnode(5)
    root.right = newnode(4)
    root.left.left = newnode(9)
    root.left.right = newnode(7)
    root.left.right.left = newnode(1)
    root.left.right.right = newnode(12)
    root.left.right.right.right = newnode(2)
    root.right.right = newnode(11)
    root.right.right.left = newnode(3)
    print("Yes") if (isPathSum(root)) else print("No")
 
# This code is contributed
# by SHUBHAMSINGH10


C#
// C# program to find if there is a pair in any root
// to leaf path with sum equals to root's key.
using System;
using System.Collections.Generic;
 
class GFG
{
 
/* A binary tree node has data,
pointer to left child and
a pointer to right child */
public class Node
{
    public int data;
    public Node left, right;
};
 
/* utility that allocates a new node with the
given data and null left and right pointers. */
static Node newnode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
 
// Function to print root to leaf path
// which satisfies the condition
static bool printPathUtil(Node node,
                          HashSet s,
                          int root_data)
{
    // Base condition
    if (node == null)
        return false;
 
    // Check if current node makes a pair
    // with any of the existing elements in set.
    int rem = root_data - node.data;
    if (s.Contains(rem))
        return true;
 
    // Insert current node in set
    s.Add(node.data);
 
    // If result returned by either left or
    // right child is true, return true.
    bool res = printPathUtil(node.left, s, root_data) ||
               printPathUtil(node.right, s, root_data);
 
    // Remove current node from hash table
    s.Remove(node.data);
 
    return res;
}
 
// A wrapper over printPathUtil()
static bool isPathSum(Node root)
{
     
    // create an empty hash table
    HashSet s = new HashSet();
     
    // Recursively check in left and right subtrees.
    return printPathUtil(root.left, s, root.data) ||
           printPathUtil(root.right, s, root.data);
}
 
// Driver code
public static void Main(String[] args)
{
    Node root = newnode(8);
    root.left = newnode(5);
    root.right = newnode(4);
    root.left.left = newnode(9);
    root.left.right = newnode(7);
    root.left.right.left = newnode(1);
    root.left.right.right = newnode(12);
    root.left.right.right.right = newnode(2);
    root.right.right = newnode(11);
    root.right.right.left = newnode(3);
    Console.Write(isPathSum(root) == true ?
                                    "Yes" : "No");
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:

Yes

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程