python--617 Merge Two Binary Trees
2018-01-23 22:04
429 查看
617. Merge Two Binary Trees
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.
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
Note: The merging process must start from the root nodes of both trees.
题意
给定了两个二叉树,要合并成一个树,也就是要将对应节点相加。最后返回即为一个树,对于某一节点,考虑以下三种情况:1)如果给定的节点为空,用其相对应的节点代替它
1)如果与其相对应的节点为空,则用这个节点代替二者的和
2)如果与其相对应的节点不为空,则将二者加起来,继续考虑该节点的左右子节点
考虑树的问题,一般要用到递归。
代码
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.right = self.mergeTrees(t1.right, t2.right) t1.left = self.mergeTrees(t1.left, t2.left) return t1
相关文章推荐
- LeetCode 617 Merge Two Binary Trees(递归合并二叉树)
- 617. Merge Two Binary Trees
- leetcode(617):Merge Two Binary Trees
- LeetCode Add to List 617 Merge Two Binary Trees (深度优先搜索)
- leetcode 617 Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 【Leetcode-easy-617】Merge Two Binary Trees
- Leetcode 617 Merge Two Binary Trees 二叉树
- Merge Two Binary Trees [LeetCode 617]
- leetcode 617 merge two binary trees
- leetcode(617). Merge Two Binary Trees
- 【LeetCode】617 Merge Two Binary Trees
- leetcode(617):Merge Two Binary Trees
- LeetCode-617-Merge Two Binary Trees-E
- 617. Merge Two Binary Trees
- LeetCode@Tree_617_Merge_Two_Binary_Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- LeetCode(617) Merge Two Binary Trees
- 617. Merge Two Binary Trees