有段时间没有写代码了,脑子都生锈了,今后争取笔耕不辍(立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. CentOS7 安装phpMyAdmin-4.8.3-all-languages

    1 需要先安装好web服务(如nginx).PHP.数据库(如MySQL) 在此略过... wget -O /tmp/phpMyAdmin--all-languages.tar.gz https:// ...

  2. numpy总结

    介绍 numpy是一个功能强大的python库.机器学习中,需要对矩阵进行各种数值计算,numpy对其提供非常好的库,用于简单和快速计算. 常用函数库 数组属性 ndarray.ndim:秩,即轴的数 ...

  3. 【转】Webdriver的PageObject改造By 张飞

    Webdriver的PageObject改造 PageObject中提供了一个@FindBy注解,也非常好用,但由于其是一次性全部初始化所有的WebElement,对于当前还不存在于页面上的Eleme ...

  4. Apache Traffic Server

    1. ats 安装 参考:https://docs.trafficserver.apache.org/en/latest/getting-started/index.en.html#installat ...

  5. 19-01【vmware machine】虚拟机无法联网访问

    问题 我本地的虚拟机上没办法访问外网,然后搞了很久很久,最终解决了. 现象 A,电脑持续运行了三天,也没有复杂的环境调整的情况下.我本地的ubuntu(使用VMWare machine创建的),突然没 ...

  6. 自动化测试框架对比(UIAutomator、Appium)

    在Android端,appium基于WebDriver协议,利用Bootstrap.jar,最后通过调⽤用UiAutomator的命令,实现App的自动化测试. UiAutomator测试框架是And ...

  7. Jenkins+Gradle+Docker打docker镜像包上传至s3

    gradle打包跟maven打包的环境搭建有相似之处,可参考maven打包https://www.cnblogs.com/chenchen-tester/p/6408815.html 进入Jenkin ...

  8. HDU 6161.Big binary tree 二叉树

    Big binary tree Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)T ...

  9. 20165213 Exp4 恶意代码分析

    恶意代码分析 实践目标 1是监控你自己系统的运行状态,看有没有可疑的程序在运行. 2是分析一个恶意软件,就分析Exp2或Exp3中生成后门软件:分析工具尽量使用原生指令或sysinternals,sy ...

  10. Windows和Frames之间的切换

    一些web应用程序有许多Frames或多个Windows. WebDriver支持使用“switchTo”的方法实现的窗口之间切换. driver.switchTo().window("wi ...