题目如下:

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. 来自鸟哥的lftp客户端软件使用方法

    lftp (自動化腳本) 單純使用 ftp 總是覺得很麻煩,有沒有更快速的 ftp 用戶軟體呢?讓我們可以使用類似網址列的方式來登入 FTP 伺服器啊?有的,那就是 lftp 的功能了! lftp 預 ...

  2. spring集成mongodb通过aop记录业务日志

    1. 编辑 pom.xml 添加 maven 依赖 <!-- mongodb --> <dependency> <groupId>org.mongodb</g ...

  3. 阶段1 语言基础+高级_1-3-Java语言高级_04-集合_01 Collection集合_4_Iterator接口介绍

    collection集合中是没有索引的,不能使用普通的循环来便利它. 也是在util的包中 先判断集合中有没有元素 有元素就取出来,用next方法 使用接口来接受一个实现类,这就是多态

  4. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_01 File类_6_File类判断功能的方法

    exists true表示路径是存在的 不存在的路径 不存在的路径返回false 相对路径的文件的判断 ‘ 不存在的相对路径 isDirectory和isFile 路径是不存在的 用这个方法之前最好先 ...

  5. Spring学习01——HelloSpring

    这是一个spring入门demo: package com.su.test; public class HelloWorld { public void say(){ System.out.print ...

  6. C# Thread2——线程优先级

    C#中Thread的优先级不是决定每个线程被执行顺序.它决定了线程可以占用CPU的时间 Thread的优先级设置是自带的枚举类型"ThreadPriority" [ComVisib ...

  7. Linux(Ubuntu)常用命令(三)

    查看时间  cal :显示当前日期.  cal :显示全年日历./ cal -y 显示当年日历.  date :显示当前时间. 这几个一般不会用到了解即可. 查看进程信息  ps :显示当前进程. - ...

  8. Python笔记(二十五)_魔法方法_描述符

    描述符的属性方法 __get__(self, instance, owner): 用于访问属性,返回属性的值 __set__(self, instance, value): 用于给属性赋值时,返回属性 ...

  9. 21次C++作业

    //第一题目 class A //A为基类 {public: void f1( ); int i; protected: void f2(); int j; private: int k; }; /* ...

  10. BZOJ 1179 (Tarjan缩点+DP)

    题面 传送门 分析 由于一个点可以经过多次,显然每个环都会被走一遍. 考虑缩点,将每个强连通分量缩成一个点,点权为联通分量上的所有点之和 缩点后的图是一个有向无环图(DAG) 可拓扑排序,按照拓扑序进 ...