Problem:
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.
Explanation:
在搜索二叉树中寻找两数之和。
My Thinking:
遍历,维护一个list存放k-当前元素.val,遍历时查询list是否由此值。
My Solution:
(1)
class Solution {
List<Integer> list=new ArrayList<>();
public boolean findTarget(TreeNode root, int k) {
if(root==null)
return false;
if(list.contains(root.val))
return true;
list.add(k-root.val);
return findTarget(root.left,k) || findTarget(root.right,k);
}
}
(2)
class Solution {
public boolean findTarget(TreeNode root, int k) {
List<Integer> list=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node=queue.poll();
if(list.contains(node.val))
return true;
list.add(k-node.val);
if(node.left!=null)
queue.add(node.left);
if(node.right!=null)
queue.add(node.right);
}
return false;
}
}
Optimum Thinking:
Optimum Solution: