Leetcode Python超琐碎笔记: 617. Merge Two Binary Trees

栏目: Python · 发布时间: 6年前

内容简介:若有错误之处请予以指正:)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.

问题地址 ,难度:Easy

若有错误之处请予以指正:)

问题描述

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.

题意分析

这道题属于一想通就能一下做出来的。首先merge树的子问题是merge节点/子树,从根节点开始,返回的结果应作为当前节点的左右子树;其次 merged tree 的结构包含了原始两个树的结构,所以可以在任选一个原始树进行in-place的merge,有的留下或者更新值,没有的补上(当这棵树上没有一个节点/子树时,把另一棵上对应的节点/子树接上来)。

树结构上的递归真是无处不在(比如Parser),一旦想清楚,实现出来往往令人觉得优雅而有趣。贴一个做这道题前没多久做的Golang练习,也是两个树之间的问题: 判断二叉查找树是否等价

我的实现及调优过程

方法1 :100 ms

暂时没有想到除此以外更好的方法。

# 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):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        return merge(t1, t2)
        
def merge(t1, t2):    
    if t1 is None:
        return t2
    elif t2 is None:
        return t1
    else:
        t1.val = t1.val + t2.val
        t1.left = merge(t1.left, t2.left)
        t1.right = merge(t1.right, t2.right)
        return t1
  • 时间复杂度:O(n) ( nmerged tree 的节点数)
  • 空间复杂度:O(1) (未创建新变量,但实际上递归本身的栈会占用一些资源)

以上所述就是小编给大家介绍的《Leetcode Python超琐碎笔记: 617. Merge Two Binary Trees》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

大教堂与集市

大教堂与集市

[美] Eric S. Raymond / 卫剑钒 / 机械工业出版社 / 2014-5 / 59.00元

当代软件技术领域最重要的著作,中文版首次出版! 《大教堂与集市》是开源运动的《圣经》,颠覆了传统的软件开发思路,影响了整个软件开发领域。作者Eric S. Raymond是开源运动的旗手、黑客文化第一理论家,他讲述了开源运动中惊心动魄的故事,提出了大量充满智慧的观念和经过检验的知识,给所有软件开发人员带来启迪。本书囊括了作者最著名的“五部曲”,并经过作者的全面更新,增加了大量注释,提高了可读......一起来看看 《大教堂与集市》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具