有段时间没有写代码了,脑子都生锈了,今后争取笔耕不辍(立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. pyautogui 文档(四):消息框功能

    消息框功能 PyAutoGUI利用PyMsgBox中的消息框函数提供跨平台的纯Python方式来显示JavaScript样式的消息框.提供了四个消息框功能: alert()函数 >>> ...

  2. 2018-2019-2 20175218 实验二《Java面向对象程序设计》实验报告

    2018-2019-2 20175218 实验二<Java面向对象程序设计>实验报告 一.面向对象程序设计-1 1.实验要求 参考 http://www.cnblogs.com/roced ...

  3. Python校验文件MD5值

    import hashlib import os def GetFileMd5(filename): if not os.path.isfile(filename): return myHash = ...

  4. 【Thread】CountdownEvent任务并行[z]

    System.Threading.CountdownEvent  是一个同步基元,它在收到一定次数的信号之后,将会解除对其等待线程的锁定. CountdownEvent  专门用于以下情况:您必须使用 ...

  5. python 获取流文件 大小

    buffer_file_content=u"流文件内容" file_size = len(buffer_file_content)/ #kb

  6. ORACLE设置用户密码不过期

    1.查看用户的 profile 是哪个,一般是 default SELECT USERNAME, PROFILE FROM dba_users; 2.查看指定概要文件(这里是1中对应的profile) ...

  7. 消息中间件和JMS介绍

    在一个公司创立初期,他可能只有几个应用,系统之间的关联也不是那么大,A系统调用B系统就直接调用B提供的API接口:后来这个公司做大了,他一步步发展有了几十个系统,这时候A系统要调用B系统的接口,但是B ...

  8. jquery.validate 远程验证remote使用详解

    目的: 试了一下远程验证,试了好几次,得出小结,可以记录下,提醒以防绕路. ----------------直接贴图,省事明了---------------- 1.引用js 2.demo的html & ...

  9. AX2009 批处理作业中使用多线程---顶级采摘

    顶级采摘 是前两种模式的一种混合,使用使用实体表存储单任务模式那样的每个工单,任务每次都取顶行做操作.单任务数不想单任务模式,一个工单一个任务.而是类似批量捆绑那样设置任务数.表:demoTopPic ...

  10. jquery中 after append appendTo 的区别

    after:在选择的元素后面添加内容,不在选择的元素内 append:在选择的元素后面的里面添加内容 appendTo:将元素添加到选择的元素里面,而且添加的元素必须是jQuery对象