给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。
案例 1:
输入: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 输出: True
案例 2:
输入: 5 / \ 3 6 / \ \ 2 4 7 Target = 28 输出: False
用哈希表记录访问过的节点。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
def find(node):
if not node:
return False
if k - node.val in nodes:
return True
nodes.add(node.val)
return find(node.left) or find(node.right)
nodes = set()
return find(root)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private Set<Integer> nodes;
public boolean findTarget(TreeNode root, int k) {
nodes = new HashSet<>();
return find(root, k);
}
private boolean find(TreeNode node, int k) {
if (node == null) {
return false;
}
if (nodes.contains(k - node.val)) {
return true;
}
nodes.add(node.val);
return find(node.left, k) || find(node.right, k);
}
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_set<int> nodes;
bool findTarget(TreeNode* root, int k) {
return find(root, k);
}
bool find(TreeNode* node, int k) {
if (node == nullptr) {
return false;
}
if (nodes.count(k - node->val)) {
return true;
}
nodes.insert(node->val);
return find(node->left, k) || find(node->right, k);
}
};
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findTarget(root *TreeNode, k int) bool {
nodes := make(map[int]bool)
var find func(node *TreeNode, k int) bool
find = func(node *TreeNode, k int) bool {
if node == nil {
return false
}
if nodes[k-node.Val] {
return true
}
nodes[node.Val] = true
return find(node.Left, k) || find(node.Right, k)
}
return find(root, k)
}