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 ...
随机推荐
- antd-react-mobile(踩坑记录)
1.按照官网步骤进行, $ npm install -g create-react-app # 注意:工具会自动初始化一个脚手架并安装 React 项目的各种必要依赖,如果在过程中出现网络问题,请尝试 ...
- 12. Integer to Roman (JAVA)
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 ...
- python中的集合
在python中,普通集合是可变数据类型 通过以下案例说明: >>> s = {1, 2, 3, 4} >>> id(s) 2108634636808 >&g ...
- 使用Spring Cache缓存出现的小失误
前文:今天在使用Spring Boot项目使用Cache中出现的小失误,那先将自己创建项目的过程摆出来 1.首先创建一个Spring Boot的项目(我这里使用的开发工具是Intellij IDEA) ...
- vue全局API
一.Vue.extend() 顾名思义 extend 继承,官方给出的解释是 (使用基础 Vue 构造器,创建一个“子类”.参数是一个包含组件选项的对象.) Vue构造器是指 vue是一个构 ...
- 20164319 刘蕴哲 Exp2 后门原理与实践
[后门概念] 后门就是不经过正常认证流程而访问系统的通道. 特指潜伏于操作系统中专门做后门的一个程序,而“坏人”可以连接这个程序远程执行各种指令. (概念和木马有重叠) [学习内容] 使用nc实现wi ...
- docker与虚拟机的区别
Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化.容器是完全使用沙箱机制,相互之间不会有任何 ...
- Django 的认识,面试题
Django 的认识,面试题 1. 对Django的认识? #1.Django是走大而全的方向,它最出名的是其全自动化的管理后台:只需要使用起ORM,做简单的对象定义,它就能自动生成数据库结构.以及全 ...
- python3 第二十六章 - 内置函数之Number相关
数学函数 函数 返回值 ( 描述 ) 实例 abs(x) 返回数字的绝对值,如abs(-10) 返回 10 print(abs(-10)) =======输出:====== 10 ceil(x) 返回 ...
- 如何选择合适的PHP版本
PHP版本很多,包括32位64位以及线程安全与非线程安全在内的php版本多达几百个,应该如何选择PHP版本呢 PHP32和64的选择和区别 32bit的php的整型数据最大最小正负2GB左右(0x7F ...