leetcode第一天-merge two binary trees
有段时间没有写代码了,脑子都生锈了,今后争取笔耕不辍(立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的更多相关文章
- 【LeetCode】617. Merge Two Binary Trees 解题报告
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...
- 【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 ...
- LeetCode算法题-Merge Two Binary Trees(Java实现)
这是悦乐书的第274次更新,第290篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第142题(顺位题号是617).提供两个二叉树,将其合并为新的二叉树,也可以在其中一个二 ...
- LeetCode 617. 合并二叉树(Merge Two Binary Trees)
617. 合并二叉树 617. Merge Two Binary Trees 题目描述 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠. 你需要将他们合并为一个新 ...
- 【Leetcode_easy】617. Merge Two Binary Trees
problem 617. Merge Two Binary Trees 参考 1. Leetcode_easy_617. Merge Two Binary Trees; 完
- 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 ...
- [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 ...
- [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 ...
- 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 ...
随机推荐
- OpenTSDB/HBase的调优过程整理
背景 过年前,寂寞哥给我三台机器,说搞个新的openTSDB集群.机器硬件是8核16G内存.3个146G磁盘做数据盘. 我说这太抠了,寂寞哥说之前的TSDB集群运行了两年,4台同样配置的机器,目前hd ...
- 第五周博客作业 <西北师范大学| 周安伟>
第五周博客作业 一,助教博客链接https://home.cnblogs.com/u/zaw-315/ 二,本周工作查阅项目汇报,班级微信群.对同学们的中期项目汇报进行查看,解决上周留言问题,对及时出 ...
- ThreadPoolExecutor源码详解
ExecutorService使用线程池中可用的线程执行每个提交的任务,这些线程通常都是使用工厂方法配置 线程池解决两种不同的问题:提高处理大量异步任务的性能(通过减少每个线程的唤醒时间) 提供一种管 ...
- 【Spring源码解析】—— 依赖注入结合SpringMVC Demo-xml配置理解
在IOC容器初始化的梳理之后,对依赖注入做一个总结,就是bean实例化的过程,bean的定义有两种方式,一种是xml文件配置,一种是注解,这里是对xml配置文件的依赖注入的介绍,后续对bean与该部分 ...
- Python学习笔记1环境搭建
1.在浏览器输入https://www.python.org/psf/,点击download下载python3.7.2(https://www.python.org/) https://www.p ...
- 《Java从入门到精通》学习总结2
1. 在JAVA语言中对静态方法有两点规定: 在静态方法中不可以使用this关键字 在静态方法中不可以直接调用非静态方法 2. 不能将方法体内的局部变量声明为static的 3. 引用只是存放一个对象 ...
- MPLAB IDE 细节点问题不定期更新ing
问题1.如何找到MPLAB IDE 隐藏的项目.输出的窗口 答:在菜单栏的 视图 中 “Project”.“Output”. 问题2.mplab c文件为什么不能添加到工程中的source file ...
- Servlet中的转发与重定向
Sevlet 的转发与重定向都可以使得浏览器指向另一个资源文件,但它们的运行机制不相同. 一.Servlet的转发 有两种方式获得转发对象(RequestDispathcer): HttpServle ...
- go的语法
概述 有接触go语言,工作中用的比较少,偶尔做个小项目,最近看到的一个项目也从go迁移到java. 但是对go还是恋恋不忘,它语法比较简洁,库也比较多,编译速度快,等等优点,让我忘不了. 对go的语法 ...
- canvas的使用方法
了解canvas:canvas标签是用作图形绘制,但是通过js脚本来实现的,canvas标签其实只是一个容器 ,最终实现绘制功能肯定是通过js脚本实现. 首先肯定要定义一个canvas标签当做容器 & ...