有关于我
我的生活
这个网站
刷题之旅
Two Sum BSTs
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.
Example 2:
Input: root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18
Output: false
Constraints:
Each tree has at most 5000 nodes. -10^9 <= target, node.val <= 10^9 Solution:
/**
* 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;
* }
* }
*/
class Solution {
public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) {
List<Integer> list = new ArrayList();
in(root1, list);
for (int val : list) {
if (bs(root2, target - val)) {
return true;
}
}
return false;
}
private void in(TreeNode root, List<Integer> list) {
if (root == null) return;
in(root.left, list);
list.add(root.val);
in(root.right, list);
}
private boolean bs(TreeNode root, int target) {
if (root == null) return false;
if (root.val == target) {
return true;
} else if (root.val < target) {
return bs(root.right, target);
} else {
return bs(root.left, target);
}
}
}
Please enable JavaScript to view the comments