177.Merge Two Binary Trees

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u010339647/article/details/79616254

题目

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.

链接

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

题目分析

很明显采用递归的思路.

  • case1:t1 == null && t2 == null ,return null;
  • case2:t1 ==null && t2 != null, return t2;
  • case3:t1 != null && t2 == null, return t1;
  • case4:t1 != null && t2 != null
    • newroot = t1.val + t2.val;
    • newroot.left = merge(t1.left, t2.left);
    • newroot.right = merge(t1.right, t2.right);
    • return newroot;

代码


class Solution(object):
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if t1 == None and t2 == None:
            return None;
        if t1 == None and t2 != None:
            return t2;
        if t1 != None and t2 == None:
            return t1;
        if t1 != None and t2 != None:
            root = TreeNode(t1.val + t2.val)
            root.left = self.mergeTrees(t1.left, t2.left)
            root.right = self.mergeTrees(t1.right, t2.right)
            return root
展开阅读全文

没有更多推荐了,返回首页