Two Sum IV - Input is a BST
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False class Solution:
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
def dfs(root, k):
if root is None:
return False
if k - root.val in st:
return True
st.add(root.val)
return dfs(root.left, k) or dfs(root.right, k)
st = set()
return dfs(root, k) class Solution:
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
def inOrder(root):
if root is None:
return
inOrder(root.left)
lst.append(root.val)
inOrder(root.right)
lst = []
inOrder(root)
# 用left和right逐渐逼近找sum == target的值
left = 0
right = len(lst) - 1
while left < right:
sm = lst[left] + lst[right]
if sm == k:
return True
elif sm > k:
right -= 1
else:
left += 1
return False class Solution {
public boolean findTarget(TreeNode root, int k) {
Set<Integer> st = new HashSet<>();
return dfs(root, k, st);
}
private boolean dfs(TreeNode root, int k, Set<Integer> st) {
if (root == null) return false;
if (st.contains(k - root.val)) return true;
st.add(root.val);
return dfs(root.left, k, st) || dfs(root.right, k, st);
}
}