📜  门| GATE-CS-2007 |第 56 题(1)

📅  最后修改于: 2023-12-03 14:58:27.532000             🧑  作者: Mango

GATE-CS-2007 Question 56

This question tests the knowledge of data structures, algorithms, and programming concepts.

Problem

Given a binary tree with $n$ nodes and an integer $k$, write a function to determine whether there exist any two nodes in the tree whose sum equals $k$.

Provide the time complexity of your algorithm.

Function Signature:

def find_sum_in_binary_tree(root: TreeNode, k: int) -> bool:
    pass

Where TreeNode is defined as:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
Example
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)

assert find_sum_in_binary_tree(root, 9) == True
assert find_sum_in_binary_tree(root, 6) == False
Explanation

In the first example, the tree has the nodes [1, 2, 3, None, None, 4, 5]. The function find_sum_in_binary_tree should return True since the nodes with values 4 and 5 add up to 9.

In the second example, the function should return False since there are no two nodes that add up to 6.

Approach

One way to solve this problem would be to use a hash set to keep track of the node values we've seen so far. We can then traverse the tree one node at a time, checking whether the difference between the current node value and k is in the hash set.

If we find a node where this difference is in the hash set, we know that there must be a node elsewhere in the tree that adds up with the current node to k. We can return True.

If we finish traversing the tree without encountering such a pair of nodes, we know there isn't one, and we can return False.

The time complexity of this algorithm is $O(n)$, since we traverse every node in the tree once.

Code
def find_sum_in_binary_tree(root: TreeNode, k: int) -> bool:
    nodes = set()
    stack = [root]
    
    while stack:
        node = stack.pop()
        
        if k - node.val in nodes:
            return True
        
        nodes.add(node.val)
        
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    
    return False
Explanation of Code

We start by initializing an empty hash set called nodes. We also create a stack and add the root node to it.

We then enter a loop where we pop one node off the stack at a time. We test whether the difference between k and the node's value is in the hash set. If it is, we know that we've seen a node with the desired value before, so we can return True.

If we haven't seen such a node before, we add the current node's value to the hash set. We then check whether the current node has any child nodes, and if so, we add them to the stack.

If we finish traversing the tree without finding a pair of nodes that add up to k, we return False.