617. 合并二叉树

https://leetcode-cn.com/problems/merge-two-binary-trees/

解法一:递归前序

思路:递归前序遍历二叉树算法的变种. 规则:

(1)若t1 和 t2都非空,访问之.并创建新节点,val为t1和t2的val之和. 然后就是前序遍历那一套

(2)若t1 t2其中有一个或两个为空,则直接返回另一个.(因为若t1已经为空,则merge之后的结果就只剩t2,直接拿过来就行.画图比较好理解)

# 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: TreeNode, t2: TreeNode) -> TreeNode:
        if t1 and t2:
            root = TreeNode(t1.val + t2.val)
            root.left = self.mergeTrees(t1.left, t2.left)
            root.right = self.mergeTrees(t1.right, t2.right)
            return root
        else:
            return t1 if t1 else t2

最后更新于