[LC] 1214. Two Sum BSTs

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 1214. 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 5Example 2

技术图片

Input: root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18
Output: false

Time: 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) {
        Set<Integer> set = new HashSet<>();
        dfs(root1, set);
        return check(root2, set, target);
    }
    
    private void dfs(TreeNode root, Set<Integer> set) {
        if (root == null) {
            return;
        }
        set.add(root.val);
        dfs(root.left, set);
        dfs(root.right, set);
    }
    
    private boolean check(TreeNode root, Set<Integer> set, int target) {
        if (root == null) {
            return false;
        }
        if (set.contains(target - root.val)) {
            return true;
        }
        return check(root.left, set, target) || check(root.right, set, target);
    }
}

 

以上是关于[LC] 1214. Two Sum BSTs的主要内容,如果未能解决你的问题,请参考以下文章

[LC]1 Two Sum

LC 1. Two Sum

LC1 Two Sum

LC 599. Minimum Index Sum of Two Lists

[LC] 170. Two Sum III - Data structure design

[LC] 167. Two Sum II - Input array is sorted