题目如下:

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. MySQL5.6transportable tablespace

    https://blog.csdn.net/xiaoyi23000/article/details/53150776

  2. 洛谷P4127同类分布

    传送 我们要在dfs的板子里记录哪些量呢?当前填的所有数的和sum?当前填的数构成的数值all? sum可以留下,数值就扔掉叭.数值最大是1e18,要是留下,在g数组里有一维的大小是1e18.也许可以 ...

  3. python安装使用(windows)

    安装 参考:http://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/install.html#scrapy 用到的文件:https://share.weiy ...

  4. mysql依据某一张表的字段,查询出对应的表所在的数据库

    表太多,只记得这个表有一个mygame的字段,但是并不知道这张表在那个数据库下,只能根据这个字段查找对应的表和所在数据库 select table_schema,table_name from inf ...

  5. 阶段1 语言基础+高级_1-3-Java语言高级_1-常用API_1_第3节 Random类_9-生成指定范围的随机数

    左闭右开区间

  6. SQLServer中的top、MySql中的limit、Oracle中的rownum

    (1)在SQL Server中,我们使用 select top N * from tablename来查询tablename表中前N条记录. (2)在MySQL中,我们使用select * from ...

  7. Linux下杀进程

    $ ps -ef | grep firefox smx : ? :: /usr/lib/firefox-/firefox-bin smx : pts/ :: grep --color=auto fir ...

  8. loading 加载工具

    loading 加载工具:http://loading.awesomes.cn/

  9. Spring Boot 集成 Ehcache 缓存,三步搞定!

    作者:谭朝红 www.ramostear.com/articles/spring_boot_ehcache.html 本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序 ...

  10. 用命令行远程导出MySQL数据

    mysqldump -h10.10.9.197 -uroot -proot --default-character-set=utf8 0610_eshop >C:/Users/Adm inist ...