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
Solution
在一棵BST中找two sum。
This is a sample approach which could be used in any tree. Using a set to store node value we have visited. Then DFS the whole tree to find if the set contains(k - node.val).
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
Set<Integer> set = new HashSet<>();
return dfs(root, set, k);
}
private boolean dfs(TreeNode node, Set<Integer> set, int k){
if (node == null){
return false;
}
if (set.contains(k - node.val)){
return true;
}
set.add(node.val);
return dfs(node.left, set, k) || dfs(node.right, set, k);
}
}
Time Complexity: O(n)
Space Complexity: O(n)
Review
We could also store the values in BST into a array then perfom two sum using two pointers.