【leetcode】1028. Recover a Tree From Preorder Traversal

题目如下:

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

原文地址:https://www.cnblogs.com/seyjs/p/10765669.html

时间: 2024-08-30 18:11:49

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

【LeetCode】Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

【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 any other value in its subtree. Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with

【LeetCode】Validate Binary Search Tree 解题报告

今天CSDN博客发生异常,折腾了大半天终于发出了这篇博文. [题目] Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a

【LeetCode】二叉查找树 binary search tree(共14题)

链接:https://leetcode.com/tag/binary-search-tree/ p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [220]Contains Duplicate III [315]Count of Smaller Numbers After Self [327]Count of Range Sum [352]Data Stream as Disjoint Intervals [493]

【LeetCode】226. Invert Binary Tree 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51527554 Subject 出处:https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. 4 / 2 7 / \ / 1 3 6 9 to 4 / 7 2 / \ / 9 6 3 1 Explain 该题目相当简单,就是一个简单的二叉树左右对换结点. Solution solution 1 递归

【一天一道LeetCode】#105. Construct Binary Tree from Preorder and Inorder Traversal

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ Given preorder and inorder traversal of a tree, construct the bin

【LeetCode】Validate Binary Search Tree 二叉查找树的判断

题目: Given a binary tree, determine if it is a valid binary search tree (BST). 知识点:BST的特点: 1.一个节点的左子树的所有点都小于或等于这个点的值,右子树的所有节点的值大于该节点的值: 2.最左节点值最小,最右节点值最大: 3.中序遍历结果值是一个非降的数列 问题:如果用Integer.MAX_VALUE会过不了测试用例,可是按照TreeNode中的定义,val值也是int呀,没办法用了Long,如果谁知道,麻烦

【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal-通过中序和后续遍历还原二叉树

一.描述: 二.思路: 二叉树的中序遍历和前序遍历或和后续遍历能唯一确定一节课二叉树,即2中还原方式都需要中序遍历才能完成: 设二叉树的前序遍历序列为{1, 2, 4, 5, 3, 6},中序遍历序列为{4,2,5,1, 3, 6}:(红色标记表示以还原节点!!!) (1)-前序遍历的第一个节点是二叉树的根节点,{1, 2, 4, 5, 3, 6},对应中序中的位置是{4,2,5,1, 3, 6},所以中序序列中的 '1' 之前的全部元素为左子树元素,'1'之后的为右子树元素: (2)-左子树对

【LeetCode】222. Count Complete Tree Nodes

Count Complete Tree Nodes Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from Wikipedia:In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last le