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 2 3
Input: root1 = [2,1,4], root2 = [1,0,3], target = 5 Output: true Explanation: 2 and 3 sum up to 5.
publicbooleantwoSumBSTs(TreeNode root1, TreeNode root2, int target){ // Convert to list List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); listByInorder(root1, list1); listByInorder(root2, list2); // Two Pointers int lo = 0, hi = list2.size() - 1; while (lo < list1.size() && hi >= 0) { // notice the condition here int sum = list1.get(lo) + list2.get(hi); if (sum == target) { returntrue; } elseif (sum < target) { ++lo; } else { --hi; } } returnfalse; }