题目如下:

We run a preorder depth first search on the root of a binary tree.

At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  (If the depth of a node is D, the depth of its immediate child is D+1.  The depth of the root node is 0.)

If a node has only one child, that child is guaranteed to be the left child.

Given the output S of this traversal, recover the tree and return its root.

Example 1:

Input: "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]

Example 2:

Input: "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]

Example 3:

Input: "1-401--349---90--88"
Output: [1,401,null,349,88,90]

Note:

  • The number of nodes in the original tree is between 1 and 1000.
  • Each node will have a value between 1 and 10^9.

解题思路:本题就是DFS的思想。首先解析Input,得到每个数值所对应的层级,接下来把Input中每个元素创建成树的节点,并且依次存入stack中。每次从Input新取出一个元素,判断其层级是否是stack中最后一个元素的层级加1,如果是表示这个节点是stack中最后一个元素的左子节点;如果是stack中倒数第二个元素的层级加1,如果是表示这个节点是stack中倒数第二个元素的右子节点;如果都不满足,stack中最后一个元素出栈,再继续做如上判断,直到找出其父节点为止。

代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def recoverFromPreorder(self, S):
"""
:type S: str
:rtype: TreeNode
"""
queue = [[0]]
dashCount = 0
val = ''
for i in S:
if i == '-':
if len(val) > 0:
queue[-1].insert(0,val)
val = ''
dashCount += 1
else:
if dashCount > 0:
queue.append([dashCount])
dashCount = 0
val += i
queue[-1].insert(0, val)
#print queue item = queue.pop(0)
root = TreeNode(int(item[0]))
nodeList = [[root,item[1]]]
while len(queue) > 0:
val,level = queue.pop(0)
while len(nodeList) > 0:
if level == nodeList[-1][1] + 1:
node = TreeNode(int(val))
nodeList[-1][0].left = node
nodeList.append([node,level])
break
elif len(nodeList) >= 2 and level == nodeList[-2][1] + 1:
node = TreeNode(int(val))
nodeList[-2][0].right = node
nodeList.append([node, level])
break
else:
nodeList.pop()
return root

【leetcode】1028. Recover a Tree From Preorder Traversal的更多相关文章

  1. [LeetCode] 1028. Recover a Tree From Preorder Traversal 从先序遍历还原二叉树

    We run a preorder depth first search on the rootof a binary tree. At each node in this traversal, we ...

  2. 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal

    Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...

  3. 【LeetCode】889. Construct Binary Tree from Preorder and Postorder Traversal 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  4. 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  5. 【LeetCode】99. Recover Binary Search Tree 解题报告(Python)

    [LeetCode]99. Recover Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/p ...

  6. 【leetcode】998. Maximum Binary Tree II

    题目如下: We are given the root node of a maximum tree: a tree where every node has a value greater than ...

  7. 【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告

    [LeetCode]106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告(Python) 标签: LeetCode ...

  8. 【LeetCode】222. Count Complete Tree Nodes 解题报告(Python)

    [LeetCode]222. Count Complete Tree Nodes 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个 ...

  9. 【LeetCode】Validate Binary Search Tree ——合法二叉树

    [题目] Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defin ...

随机推荐

  1. p2p传输协议

    老司机是如何飙车的——P2P传输协议 转载来自2017-03-27 15:23 点波蓝字关注变智者 秋明山上人行稀,常有车手较高低,如今车道依旧在,不见当年老司机.其实老司机们从未离去,只不过好的车手 ...

  2. MySQL闪回工具之myflash 和 binlog2sql

    MySQL闪回工具之:binlog2sql  https://github.com/danfengcao/binlog2sql MYSQL Binglog分析利器:binlog2sql使用详解  :h ...

  3. AtomicReference 源码分析

    AtomicReference AtomicReference 能解决什么问题?什么时候使用 AtomicReference? 1)AtomicReference 可以原子更新引用对象. 2)comp ...

  4. Openstack 通过 SQLAlchemy-ORM 访问数据库

    目录 目录 Demo SQLAlchemy 数据库的初始化 数据库的操作实现 数据库的操作请求 全部查询 单个查询 创建 更新 删除 Demo Github/JmilkFan/my-code-repe ...

  5. 《图解设计模式》读书笔记8-3 STATE模式

    目录 State模式 示例程序 实现的功能 不使用&使用状态模式对比 示例程序的类图 代码 角色和类图 角色 类图 拓展思路 分而治之 依赖于状态的处理 谁来管理状态迁移 易于增加新状态 实例 ...

  6. 前端框架React入门课程【视频】

    视频教程列表: http://v1.mukewang.com/1a8228ac-5f7f-48de-b1c5-7d1b8bce9c77/L.mp4 1-1 React入门课程介绍 http://v1. ...

  7. python绘制五角星

    问题描述: python中运用turtle图形模块绘制五角星 问题分析: turtle绘制图形时,得知图形中重要点的坐标非常重要. 于是,绘制五角星问题转化成为一个数学问题,计算五个顶点坐标即可. 已 ...

  8. vue 父子component生命周期

    如今前端框架都流行组件化,页面元素都可以使用组件进行高度概括,那么处理组件之间的关系就如同处理页面架构一样重要.正确理解组件之间的关系,才能让代码按照我们与预料方式工作.最近参与了一个Vue.js的项 ...

  9. pyenv python 版本控制

    经常遇到这样的情况: 系统自带的Python是2.x,自己需要Python 3.x,此时需要在系统中安装多个Python,但又不能影响系统自带的Python,即需要实现Python的多版本共存,pye ...

  10. VLAN 基础设置及Aceess接口

    实验内容 本实验模拟企业网络场景.公司内网是一一个大的局域网,二层交换机S1放置在一楼,在一楼办公的部门有IT部和人事部;二层交换机S2放置在二楼,在二楼办公的部门有市场部和研发部.由于交换机组成的是 ...