题目要求

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

题目分析及思路

题目给出两个二叉树,要求得到一棵融合的二叉树,融合规则是有重叠的结点的值是原先结点的值的和,否则作为新树的结点。可以遍历每个结点然后如果重叠(两个二叉树结点都不为空)新结点值便为两者和,不重叠(只有一个结点为空)新结点值为不为空的值,全为空则跳出。按照这个逻辑进行迭代。

python代码​

# Definition for a binary tree node.

# class TreeNode:

#     def __init__(self, x):

#         self.val = x

#         self.left = None

#         self.right = None

class Solution:

def mergeTrees(self, t1, t2):

"""

:type t1: TreeNode

:type t2: TreeNode

:rtype: TreeNode

"""

if t1 is None and t2 is None:

return

if t1 is None:

return t2

if t2 is None:

return t1

t1.val += t2.val

t1.left = self.mergeTrees(t1.left,t2.left)

t1.right = self.mergeTrees(t1.right,t2.right)

return t1

最新文章

  1. 20145212&20145204信息安全系统实验四报告
  2. easyui相关script的配置
  3. easyUI 中datagrid 返回列隐藏方法
  4. 阿里巴巴B2B搜索学习
  5. jstl标签
  6. 简单的angular表单验证指令
  7. nginx下面server配置
  8. POJ 1190(深搜)
  9. ROS探索总结(三)——ROS新手教程【转】
  10. netty定时器HashedWheelTimer(zz)
  11. Deep Learning论文笔记之(四)CNN卷积神经网络推导和实现(转)
  12. BAT CMD 批处理文件脚本 -2
  13. 为了圣像画系统V1.0Beta版(javascript)-GIS520社区
  14. 这个夏天不AC(杭州电2037)
  15. git add -f
  16. zc702-自定义AXI-IP核实验
  17. ipsec在企业网中的应用(IKE野蛮模式)(转)
  18. Codeforces 913C - Party Lemonade
  19. hihocoder #1076 与链 dp
  20. 解决ueditor中没法动态配置imageurlprefix的方法

热门文章

  1. rc.d/rc.local 自动启 tomcat 启不来
  2. linux设置开机自启动
  3. 【iCore4 双核心板_ARM】例程十八:USBD_VCP实验——虚拟串口
  4. CentOS服务器ntpdate同步
  5. spring boot 2整合swagger-ui
  6. python日志,一个改版SMTPHandler
  7. [IR] Advanced XML Compression - ISX
  8. ios开发之--关于UIView的autoresizingMask属性的研究
  9. vue编程式路由实现新窗口打开
  10. TIScript Graphics