LeetCode 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.

题目分析及思路

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

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):

扫描二维码关注公众号,回复: 5006838 查看本文章

        """

        :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

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10297733.html