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 ...
随机推荐
- Heroku登录问题
second_app 这一步还没有完成,登录接口维护.
- volatile和synchronized实现内存可见性的区别
先看看synchronized实现内存可见性 加锁(synchronized同步)的功能不仅仅局限于互斥行为,同时还存在另外一个重要的方面:内存可见性.我们不仅希望防止某个线程正在使用对象状态而另一个 ...
- 混合现实开发教程unity2017
共52节,MP4格式,英字,大小1GB 扫码时备注或说明中留下邮箱 付款后如未回复请至https://shop135452397.taobao.com/ 联系店主
- jdk和tomcat的安装
https://blog.csdn.net/angel_w/article/details/78580528
- js 加减乘除以及四舍五入 新写法
1 四舍五入 eg: (1.23).round() = 1.2 (1.2456).round(3) = 1.246 Number.prototype.round = function (count) ...
- 13. Redis监控运维云平台CacheCloud
13. Redis监控运维云平台CacheCloud13.1 CacheCloud是什么13.1.1 现有问题13.1.2 CacheCloud基本功能13.2 快速部署13.2.1 CacheClo ...
- 从阿里巴巴面试题到java类加载机制
首先很经典的阿里巴巴面试题 加上我自己的一些疑惑代码 public class Text { public static int k = 0; public final int k1 = 3; //自 ...
- DOM生成XML文件
/** * 从数据库读取学生信息的数据集合,然后Dom创建数据树,再转成XML格式数据,输出生成xml文件 * @author pikaqiu * */ public class TestGenXml ...
- kettle连接oracle报错oracle.i18n.text.converter.CharacterConverter.OGS.getInstance(I)Loracle/i18n/text/converter/CharacterConverter
问题背景1:需要将一张excel中的数据导入到数据库中,并且还有关联转换和去重的处理问题,且此excel表不是固定的,需要写一个脚本 当新的excel拿来的时候,可以直接导入即可.所以我想用kettl ...
- cpu的工作原理