Description
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
分析
题目的意思是:给定一颗二叉树,判断是否存在两个数的和为target。
- 用一个set集合s把来存储每个节点的值,如果再遇见一个target-当前值存在这个集合里面,说明存在两个数,就直接返回正确了。
C++实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
if(!root) return false;
unordered_set<int> s;
return solve(root,k,s);
}
bool solve(TreeNode* root, int k,unordered_set<int> &s){
if(!root){
return false;
}
if(s.count(k-root->val)){
return true;
}
s.insert(root->val);
return solve(root->left,k,s)||solve(root->right,k,s);
}
};
Python实现
# 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 dfs(self, root, k, st):
if not root:
return False
if k-root.val in st:
return True
st.append(root.val)
return self.dfs(root.left,k,st) or self.dfs(root.right,k,st)
def findTarget(self, root: TreeNode, k: int) -> bool:
res = []
return self.dfs(root,k,res)
本文探讨了如何在二叉搜索树中寻找两个元素,使其和等于给定的目标值。通过使用集合存储节点值,检查目标值与当前值的差是否存在于集合中,从而高效地解决该问题。提供了C++和Python的实现代码。
336

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



