|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import com.fishercoder.common.classes.TreeNode; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +/** |
| 9 | + * 1214. Two Sum BSTs |
| 10 | + * |
| 11 | + * Given two binary search trees, |
| 12 | + * 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. |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * 2 1 |
| 16 | + * / \ / \ |
| 17 | + * 1 4 0 3 |
| 18 | + * |
| 19 | + * Input: root1 = [2,1,4], root2 = [1,0,3], target = 5 |
| 20 | + * Output: true |
| 21 | + * Explanation: 2 and 3 sum up to 5. |
| 22 | + * |
| 23 | + * Example 2: |
| 24 | + * 0 5 |
| 25 | + * / \ / \ |
| 26 | + * -10 10 1 7 |
| 27 | + * / \ |
| 28 | + * 0 2 |
| 29 | + * |
| 30 | + * Input: root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18 |
| 31 | + * Output: false |
| 32 | + * |
| 33 | + * Constraints: |
| 34 | + * Each tree has at most 5000 nodes. |
| 35 | + * -10^9 <= target, node.val <= 10^9 |
| 36 | + * */ |
| 37 | +public class _1214 { |
| 38 | + public static class Solution1 { |
| 39 | + public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) { |
| 40 | + if (root1 == null || root2 == null) { |
| 41 | + return false; |
| 42 | + } |
| 43 | + List<Integer> inorder1 = inorderDfs(root1, new ArrayList<>()); |
| 44 | + List<Integer> inorder2 = inorderDfs(root2, new ArrayList<>()); |
| 45 | + return findTwoSum(inorder1, inorder2, target); |
| 46 | + } |
| 47 | + |
| 48 | + private boolean findTwoSum(List<Integer> sorted1, List<Integer> sorted2, int target) { |
| 49 | + for (int i = 0; i < sorted1.size(); i++) { |
| 50 | + if (exists(sorted2, target - sorted1.get(i))) { |
| 51 | + return true; |
| 52 | + } |
| 53 | + } |
| 54 | + return false; |
| 55 | + } |
| 56 | + |
| 57 | + private boolean exists(List<Integer> sorted, int target) { |
| 58 | + int left = 0; |
| 59 | + int right = sorted.size() - 1; |
| 60 | + while (left <= right) { |
| 61 | + int mid = left + (right - left) / 2; |
| 62 | + if (sorted.get(mid) == target) { |
| 63 | + return true; |
| 64 | + } else if (sorted.get(mid) < target) { |
| 65 | + left = mid + 1; |
| 66 | + } else { |
| 67 | + right = mid - 1; |
| 68 | + } |
| 69 | + } |
| 70 | + return false; |
| 71 | + } |
| 72 | + |
| 73 | + private List<Integer> inorderDfs(TreeNode root, List<Integer> list) { |
| 74 | + if (root == null) { |
| 75 | + return list; |
| 76 | + } |
| 77 | + if (root.left != null) { |
| 78 | + list = inorderDfs(root.left, list); |
| 79 | + } |
| 80 | + list.add(root.val); |
| 81 | + if (root.right != null) { |
| 82 | + list = inorderDfs(root.right, list); |
| 83 | + } |
| 84 | + return list; |
| 85 | + } |
| 86 | + |
| 87 | + } |
| 88 | +} |
0 commit comments