首页 > 其他 > 详细

[LC] 1214. Two Sum BSTs

时间:2020-04-27 12:39:42      阅读:48      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/xuanlu/p/12785735.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!