Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
Solution:
#traverse the tree and using's hash to store visited node
dic = {}
def helperRecursive(root):
if root is None:
return False
if (k - root.val) in dic:
return True
if root.val not in dic:
dic[root.val] = 1
return helperRecursive(root.left) or helperRecursive(root.right)
return helperRecursive(root)
本文介绍了一种在二叉搜索树中查找是否存在两个元素之和等于给定目标值的方法。通过递归遍历树,并使用哈希表记录已访问节点,实现了高效查找。给出两个示例说明了该方法的有效性和正确性。
426

被折叠的 条评论
为什么被折叠?



