Easy
Given the root
of a Binary Search Tree and a target number k
, return true
if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input: root = [5,3,6,2,4,null,7], k = 9
Output: true
Example 2:
Input: root = [5,3,6,2,4,null,7], k = 28
Output: false
Constraints:
[1, 104]
.-104 <= Node.val <= 104
root
is guaranteed to be a valid binary search tree.-105 <= k <= 105
import com_github_leetcode.TreeNode;
import java.util.ArrayList;
import java.util.List;
/*
* 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;
* }
* }
*/
public class Solution {
public boolean findTarget(TreeNode root, int k) {
if (root == null) {
return false;
}
List<Integer> res = new ArrayList<>();
inOrder(res, root);
int i = 0;
int j = res.size() - 1;
while (i < j) {
int val1 = res.get(i);
int val2 = res.get(j);
if (val1 + val2 == k) {
return true;
} else if (val1 + val2 < k) {
i++;
} else {
j--;
}
}
return false;
}
private void inOrder(List<Integer> res, TreeNode root) {
if (root == null) {
return;
}
inOrder(res, root.left);
res.add(root.val);
inOrder(res, root.right);
}
}