题意
给定一颗二叉搜索树,返回是否存在两个节点的值之和为给定值K.
思路
同Two Sum.使用Hash表解决。只是要写个树的遍历而已,选取DFS.
源码
class Solution {
public boolean findTarget(TreeNode root, int k) {
return work(root,k,new HashSet<Integer>());
}
private boolean work(TreeNode root,int k,Set<Integer>s) {
if (root == null)
return false;
if (s.contains(k-root.val))
return true;
s.add(root.val);
if (work(root.left,k,s) || work(root.right,k,s))
return true;
return false;
}
}
结果
Runtime: 14 ms, faster than 85.59% of Java online submissions for Two Sum IV - Input is a BST.
Memory Usage: 43.9 MB, less than 100.00% of Java online submissions for Two Sum IV - Input is a BST.