首页 > 其他 > 详细

leetcode-第10周双周赛-5080-查找两颗二叉搜索树之和

时间:2019-10-07 14:20:33      阅读:135      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

 技术分享图片

 

 

自己的提交:

class Solution:
    def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool:
        if not root1 :return 
        root_copy = root2
        while root1 and root_copy:
            if root1.val + root_copy.val < target:
                root_copy = root_copy.right
            elif root1.val + root_copy.val > target:
                root_copy = root_copy.left
            else:return True
        if self.twoSumBSTs(root1.left,root2,target):
            return True
        if self.twoSumBSTs(root1.right,root2,target):
            return True
        return False
        

另:

class Solution(object):
    def twoSumBSTs(self, root1, root2, target):
        ans1 = []
        def dfs1(node):
            if node:
                dfs1(node.left)
                ans1.append(node.val)
                dfs1(node.right)
        ans2 = []
        def dfs2(node):
            if node:
                dfs2(node.left)
                ans2.append(node.val)
                dfs2(node.right)
        dfs1(root1)
        dfs2(root2)
        seen = set(ans1)
        for x in ans2:
            if target-x in seen:
                return True
        return False

优化:

class Solution:
    def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool:
        def conv(root):
            if not root:
                return []
            else:
                return [root.val] + conv(root.left) + conv(root.right)
        r1 = conv(root1)
        r2 = conv(root2)
        r1 = set(r1)
        r2 = set(r2)
        for i in r1:
            if target - i in r2:
                return True
        return False

 

leetcode-第10周双周赛-5080-查找两颗二叉搜索树之和

原文:https://www.cnblogs.com/oldby/p/11630151.html

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