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:
The inorder sequence of BST is sorted.
So firstly we use O(n) time to construct a sorted ArrayList.
After that, we can apply two pointers from the start and end of the ArrayList to search for a target sum.
The time complexity of the search is also (n).
Thus, the time complexity is O(n) and the space complexity is O(n).
Code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean findTarget(TreeNode root, int k) { List<Integer> list = new ArrayList<>(); inorder(root, list); int i = 0; int j = list.size() - 1; while (i < j) { int sum = list.get(i) + list.get(j); if (sum == k) { return true; } else if (sum < k) { i++; } else { j--; } } return false; } public List<Integer> inorder(TreeNode root, List<Integer> list) { Stack<TreeNode> stack = new Stack<>(); while (root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); list.add(root.val); root = root.right; } return list; } }