Given two binary search trees, return True
if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer target
.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3], target = 5
Output: true
Explanation: 2 and 3 sum up to 5.
思路:就是个hashset存target - node.val, 两个inorder traverse;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) {
if(root1 == null || root2 == null) {
return false;
}
HashSet<Integer> set = new HashSet<Integer>();
traverse(root1, set, target, true);
return traverse(root2, set, target, false);
}
private boolean traverse(TreeNode root, HashSet<Integer> set,
int target, boolean traverse) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while(node != null) {
stack.push(node);
node = node.left;
}
while(!stack.isEmpty()) {
node = stack.pop();
if(traverse) {
set.add(target - node.val);
} else {
if(set.contains(node.val)) {
return true;
}
}
if(node.right != null) {
node = node.right;
while(node != null) {
stack.push(node);
node = node.left;
}
}
}
return false;
}
}
思路2:用两个stack,stack1走到最左边,stack2走到最右边,然后sum < target, 走左边,sum>target走右边;O(M + N);
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) {
if(root1 == null || root2 == null) {
return false;
}
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
TreeNode t1, t2;
while(true) {
while(root1 != null) {
stack1.push(root1);
root1 = root1.left;
}
while(root2 != null) {
stack2.push(root2);
root2 = root2.right;
}
if(stack1.isEmpty() || stack2.isEmpty()) {
break;
}
t1 = stack1.peek();
t2 = stack2.peek();
int sum = t1.val + t2.val;
if(sum == target) {
return true;
} else if(sum < target) {
stack1.pop();
root1 = t1.right;
} else {
// sum > target;
stack2.pop();
root2 = t2.left;
}
}
return false;
}
}