617.Merge Two Binary Trees(合并两棵树)
2017-10-07 21:17
344 查看
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.
您需要将它们合并成一个新的二叉树。合并规则是如果两个节点重叠,则sum节点值作为合并节点的新值。否则,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.
您需要将它们合并成一个新的二叉树。合并规则是如果两个节点重叠,则sum节点值作为合并节点的新值。否则,NOT空节点将被用作新树的节点。
Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7
思路:
考察的就是二叉树的遍历,遍历每个结点然后如果重叠(两个二叉树结点都不为空)新结点值便为两者和,不重叠(只有一个结点为空)新结点值为不为空的值,全为空到达底部返跳出。按照这个逻辑进行迭代
联想:二叉树遍历方式有深度优先和广度优先,深度(纵向)优先在Python中一般使用列表,广度优先(横向)一般使用迭代
# 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 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.right = self.mergeTrees(t1.right, t2.right) t1.left = self.mergeTrees(t1.left, t2.left) return t1
相关文章推荐
- Oracle合并多行为多列
- PHP把2个二维数组合并一个二维数组2种解法
- c++学习笔记:有序链表的合并
- mysql多行多列合并为一行一列 【转】
- CUDA性能调优(一)--合并访问&循环展开
- 子网划分与子网合并
- 合并数据
- 神奇的操作——线段树合并(例题: BZOJ2212)
- 利用python将夏普WG-S20输出的BMP转化成pdf并合并
- SAP HANA SQL合并多行操作
- 合并复制方法
- SQL 查出多条数据 用逗号隔开 合并某一列的 标量函数
- SPOJ FTOUR2 (平衡树+启发式合并/点分治)
- Vijos P1097 合并果子(优先队列 贪心)
- 合并区间
- 如何合并GridView中的单元格
- SQLite3 一列多行合并为一列一行 分类: 数据库 2013-06-25 17:02 1251人阅读 评论(0) 收藏
- 四、数据规整化:清洗、转换、合并和重塑
- svn 合并的问题
- 02-线性结构1 两个有序链表序列的合并