题目如下:

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

最新文章

  1. 浅谈CSS hack(浏览器兼容)
  2. 【原】理解javascript中的闭包
  3. canvas基本用法
  4. 从Wep page到Application
  5. GDB中应该知道的几个调试方法 来自陈皓
  6. htop
  7. C#使用Process类调用外部程序(转)
  8. in和exists哪个效率高本人测试证明
  9. 【Scala】Scala之Methods
  10. linux操作系统基础篇(四)
  11. oracle有三种类型的异常错误: 预定义 ( Predefined )错误里面的常见错误
  12. js显示屏幕分辨率
  13. JDBC:随机生成车牌号,批量插入数据库
  14. tf.assign,tf.assign_add,tf.assign_sub
  15. DBExportDoc V1.0 For MySQL
  16. Android - Builder模式
  17. mysqldump 导出统一限制每张数据表导出的记录数
  18. 用Netty开发中间件:高并发性能优化(转)
  19. Laravel 5.x HTTPS反向代理的实现
  20. Java学习笔记01

热门文章

  1. linux进阶命令
  2. mybatis 动态SQL .2
  3. crond服务总结
  4. docker 安装 nexus
  5. djangourl进阶
  6. javascript 数据类型之数值转换
  7. Vue 进阶系列(一)之响应式原理及实现
  8. 洛谷 P2331 最大子矩阵 题解
  9. UVA 1642 MagicalGCD 题解
  10. 推荐几本Python书