首页 > 其他 > 详细

【leetcode】1214.Two Sum BSTs

时间:2019-10-07 09:17:06      阅读:78      评论: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 5.

Example 2:

技术分享图片技术分享图片

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

 

Note:

  1. Each tree has at most 5000 nodes.
  2. -10^9 <= target, node.val <= 10^9

解题思路:我用的是最直接的方法,把两棵树的节点的值分别存到两个字典中,然后遍历字典,看看能不能组成target。

代码如下:

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def twoSumBSTs(self, root1, root2, target):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :type target: int
        :rtype: bool
        """
        dic1 = {}
        dic2 = {}
        def recursive(node,dic):
            if node != None:
                dic[node.val] = 1
            if node.left != None:
                recursive(node.left,dic)
            if node.right != None:
                recursive(node.right, dic)
        recursive(root1,dic1)
        recursive(root2,dic2)
        for val in dic1.iterkeys():
            if target - val in dic2:
                return True
        return False

 

【leetcode】1214.Two Sum BSTs

原文:https://www.cnblogs.com/seyjs/p/11629275.html

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