题目描述
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.
方法思路
这道题目相对简单,只要遍历了数组并进行查找即可,相比较而言,中序遍历要比先序遍历更好一点,因为前者利用了BST的结构特性。
Approach1: based on preorder
class Solution {
//Runtime: 13 ms, faster than 78.49%
//Memory Usage: 46.4 MB, less than 24.87%
List<Integer> list;
public boolean findTarget(TreeNode root, int k) {
list = new ArrayList<>();
dfs(root);
for(int i = 0; i < list.size(); i++){
//要考虑到k = 2 * list.get(i)的情况
if(list.contains(k - list.get(i)) && k != 2 * list.get(i))
return true;
}
return false;
}
public void dfs(TreeNode root){
if(root == null) return;
list.add(root.val);
dfs(root.left);
dfs(root.right);
return;
}
}
Approach2: based on inorder
public class Solution {
//Runtime: 12 ms, faster than 91.82%
//Memory Usage: 44.8 MB, less than 33.89%
public boolean findTarget(TreeNode root, int k) {
List < Integer > list = new ArrayList();
inorder(root, list);
int l = 0, r = list.size() - 1;
while (l < r) {
int sum = list.get(l) + list.get(r);
if (sum == k)
return true;
if (sum < k)
l++;
else
r--;
}
return false;
}
public void inorder(TreeNode root, List < Integer > list) {
if (root == null)
return;
inorder(root.left, list);
list.add(root.val);
inorder(root.right, list);
}
}