题目如下:

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. Linux 下wdcp支持两种安装方式

    wdcp支持两种安装方式1 源码编译 此安装比较麻烦和耗时,一般是20分钟至一个小时不等,具体视机器配置情况而定2 RPM包安装 简单快速,下载快的话,几分钟就可以完成源码安装(ssh登录服务器,执行 ...

  2. fedora禁用(开机启动)服务和进程管理

    首先要查看有哪些(开机启动)服务 chkconfig --list 或者: systemctl list-units 然后, 根据需要进行禁用服务的开机启动: chkconfig service_na ...

  3. 用Vue来实现音乐播放器(10):Scroll组件的抽象和应用

    了解better-scroll什么时候是需要refresh计算的??通常我们遇到的better-scroll不能滚动的问题的根源是什么??better-scroll的渲染原理是:根据初始化的时机  或 ...

  4. VMware 虚拟化编程(1) — VMDK/VDDK/VixDiskLib/VADP 概念简析

    目录 目录 VMDK VDDK VixDiskLib VADP VMDK VMDK(VMware's Virtual Machine Disk Format,VMware 虚拟磁盘格式):简单来说就是 ...

  5. 阶段1 语言基础+高级_1-3-Java语言高级_02-继承与多态_第7节 内部类_7_内部类的概念与分类

    完整

  6. 16/7/7_PHP-构造\解析函数

    昨天又问老师问题,老师还是强调要用博客之类记录下每天的学习的习惯. 我个人的想法是一些知识点不用笔记一下 在脑海的理解不是太深.但是老师都这么说了我老师乖乖的记录下今天的学习的一些知识.心得.技巧等等 ...

  7. Babel编译:动态计算的属性名

    ES2015允许使用表达式作为属性名. 编译前: const HELLO = 'hello'; let dog = { [HELLO](){ console.log('hello'); } } 编译后 ...

  8. spring Cloud 之 Eureka、Feign、Hystrix、Zuul、Config、Bus

    一.服务发现——Netflix Eureka Eureka包含两个组件: Eureka Server和Eureka Client 1.创建Eureka Server服务端 (1).引入依赖 父工程po ...

  9. oracle linux 7使用udev绑盘操作

    参考:Oracle Linux 7: Udev rule for ASM Cannot Place the ASM Disk in a Directory under /dev (Doc ID 221 ...

  10. Proteus报错处理经验:power rails ‘GND’ and 'VCC/VDD' are interconnected in net VCC

    1 前言 初学Proteus,画好原理图后遇到了power rails 'GND' and 'VCC/VDD' are interconnected in net VCC的报错. 尝试了网上的解决办法 ...