有段时间没有写代码了,脑子都生锈了,今后争取笔耕不辍(立flag,以后打脸)

随机一道Leecode题, 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.

题目是很简单的题目,但是由于大脑生锈,竟然也折腾了半天。

解题思路是使用迭代。

令tree1为t1,tree2为t2

merge tree的root肯定为t1.root+t2.root

对于merge tree的left,可以认为是以t1.left为root的tree与以t2.left为root的tree合并的结果

同样类似,对于merge tree的right,可以认为是t1.right为root的tree与以t2.right为root的tree合并的结果

如此反复,通过迭代就很容易得到结果了。

做个备忘,在python3中,使用TreeNode来构建树,树当前的节点的值为val,节点的左子节点为left,节点的右子为right.

代码如下:

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.left = self.mergeTrees(t1.left,t2.left)
t1.left = self.mergeTrees(t1.right,t2.right)
return t1 def stringToTreeNode(input):
input = input.strip()
input = input[1:-1]
if not input:
return None
inputValues = [s.strip() for s in input.split(',')]
root = TreeNode(int(inputValues[0]))
nodeQueue = [root]
front = 0
index = 1
while index < len(inputValues):
node = nodeQueue[front]
front = front + 1 item = inputValues[index]
index = index + 1
if item != "null":
leftNumber = int(item)
node.left = TreeNode(leftNumber)
nodeQueue.append(node.left) if index >= len(inputValues):
break item = inputValues[index]
index = index + 1
if item != "null":
rightNumber = int(item)
node.right = TreeNode(rightNumber)
nodeQueue.append(node.right)
return root def treeNodeToString(root):
if not root:
return "[]"
output = ""
queue = [root]
current = 0
while current != len(queue):
node = queue[current]
current = current + 1 if not node:
output += "null, "
continue output += str(node.val) + ", "
queue.append(node.left)
queue.append(node.right)
return "[" + output[:-2] + "]" def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n') lines = readlines()
while True:
try:
line = next(lines)
t1 = stringToTreeNode(line);
line = next(lines)
t2 = stringToTreeNode(line); ret = Solution().mergeTrees(t1, t2) out = treeNodeToString(ret);
print(out)
except StopIteration:
break if __name__ == '__main__':
main()

leetcode第一天-merge two binary trees的更多相关文章

  1. 【LeetCode】617. Merge Two Binary Trees 解题报告

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  2. 【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 o ...

  3. LeetCode算法题-Merge Two Binary Trees(Java实现)

    这是悦乐书的第274次更新,第290篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第142题(顺位题号是617).提供两个二叉树,将其合并为新的二叉树,也可以在其中一个二 ...

  4. LeetCode 617. 合并二叉树(Merge Two Binary Trees)

    617. 合并二叉树 617. Merge Two Binary Trees 题目描述 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠. 你需要将他们合并为一个新 ...

  5. 【Leetcode_easy】617. Merge Two Binary Trees

    problem 617. Merge Two Binary Trees     参考 1. Leetcode_easy_617. Merge Two Binary Trees; 完    

  6. Week2 - 669. Trim a Binary Search Tree & 617. Merge Two Binary Trees

    Week2 - 669. Trim a Binary Search Tree & 617. Merge Two Binary Trees 669.Trim a Binary Search Tr ...

  7. [LeetCode] Merge Two Binary Trees 合并二叉树

    Given two binary trees and imagine that when you put one of them to cover the other, some nodes of t ...

  8. [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 t ...

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

随机推荐

  1. python的re模块详解

    一.正则表达式的特殊字符介绍 正则表达式 ^ 匹配行首 $ 匹配行尾 . 任意单个字符 [] 匹配包含在中括号中的任意字符 [^] 匹配包含在中括号中的字符之外的字符 [-] 匹配指定范围的任意单个字 ...

  2. vue.js 进行初始化遇到的关于core-js的错误@core-js/modules/es6.array.find-index]

    D:\vuejselement\workSpace\zutnlp_platform_show>cnpm install --save core-js/modules/es6.array.find ...

  3. vmware 挂起后不能恢复

    报错:未能锁定主内存文件,还原虚拟机状态时出错 虚拟机目录下有一个文件夹,xxx.vmem.lck,里面的lck文件是很久以前的,把它删掉重新恢复就可以了.

  4. 分析easyswoole3.0源码,体验es3(三)

    demo在手,总得去试试看效果吧.我们先把默认的服务改成webserver,并且添加数据库的配置. 建立数据库,github里面有相关内容 CREATE TABLE `user_list` ( `us ...

  5. python中的深浅copy

    https://www.cnblogs.com/Eva-J/p/5534037.html 转自Eva_J  分析的特别好

  6. Texture转Texture2D

    private Texture2D TextureToTexture2D(Texture texture) { Texture2D texture2D = new Texture2D(texture. ...

  7. MySql共享锁和排它锁

    共享锁和排他锁 1.共享锁: 读锁.X锁,在查询时生效,多个事务在查询同一个数据时共享一把锁,但是不能作用于修改数据,在select语句后添加 lock in share mode : 2.排他锁:在 ...

  8. mysql触发器trigger 实例详解

    mysql触发器trigger 实例详解 (转自 https://www.cnblogs.com/phpper/p/7587031.html)   MySQL好像从5.0.2版本就开始支持触发器的功能 ...

  9. 基于百词斩和扇贝单词的背单词APP软件测试

    概述 背单词APP是非常受大学生青睐的手机应用,但它的发展尚未成熟,存在一些缺陷.我们决定深入地分析一组典型的背单词APP:百词斩(A产品).扇贝单词(B产品),寻找当前背单词APP中的提升空间.下面 ...

  10. python语法之正则

    1.正则表达式是用来干嘛的? 用来匹配字符串的  ,其中正则是意思是模糊匹配. 就其本质而言,正则表达式(或 RE)是一种小型的.高度专业化的编程语言,(在Python中)它内嵌在Python中,并通 ...