资讯专栏INFORMATION COLUMN

LeetCode 331. Verify Preorder Serialization of a B

张巨伟 / 1130人阅读

摘要:如果它是一个空节点,我们可以使用一个标记值记录,例如。例如,上面的二叉树可以被序列化为字符串,其中代表一个空节点。每个以逗号分隔的字符或为一个整数或为一个表示指针的。如果满足前序遍历,那么最后栈中有且仅有一个元素,且是。

Description

One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node"s value. If it is a null node, we record using a sentinel value such as #.

     _9_
    /   
   3     2
  /    / 
 4   1  #  6
/  /    / 
# # # #   # #

For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node.

Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.

Each comma separated value in the string must be either an integer or a character "#" representing null pointer.

You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".

Example 1:

Input: "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: true
Example 2:

Input: "1,#"
Output: false
Example 3:

Input: "9,#,#,1"
Output: false

描述

序列化二叉树的一种方法是使用前序遍历。当我们遇到一个非空节点时,我们可以记录下这个节点的值。如果它是一个空节点,我们可以使用一个标记值记录,例如 #。

     _9_
    /   
   3     2
  /    / 
 4   1  #  6
/  /    / 
# # # #   # #

例如,上面的二叉树可以被序列化为字符串 "9,3,4,#,#,1,#,#,2,#,6,#,#",其中 # 代表一个空节点。

给定一串以逗号分隔的序列,验证它是否是正确的二叉树的前序序列化。编写一个在不重构树的条件下的可行算法。

每个以逗号分隔的字符或为一个整数或为一个表示 null 指针的 "#" 。

你可以认为输入格式总是有效的,例如它永远不会包含两个连续的逗号,比如 "1,,3" 。

示例 1:

输入: "9,3,4,#,#,1,#,#,2,#,6,#,#"
输出: true
示例 2:

输入: "1,#"
输出: false
示例 3:

输入: "9,#,#,1"
输出: false

思路

使用栈,如果两个 # 连续出现,根据前序遍历的定义,前面一个一定是叶子节点,我们将这两个 # 弹出,然后将叶子节点重置为 None (即#),如此循环下去。

如果满足前序遍历,那么最后栈中有且仅有一个元素,且是 # 。

# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-03-17 09:44:27
# @Last Modified by:   何睿
# @Last Modified time: 2019-03-17 10:03:55


class Solution:
    def isValidSerialization(self, preorder: str) -> bool:
        # stack:用于记录遍历到的节点值
        # count:stack 中剩余的节点个数
        stack, count = [], 0
        for item in preorder.split(","):
            stack.append(item)
            count += 1
            # 如果 stack 中末位两个元素是 #,说明这两个节点前面是一个叶子节点
            # 将两个 # 弹出 ,将叶子节点置为 None,即 #
            # 如果是前序遍历,那么 stack 最后一定会剩下一个 # 
            while count > 1 and stack[-1] == "#" and stack[-2] == "#":
                stack.pop()
                stack.pop()
                if not stack: return False
                stack[-1] = "#"
                count -= 2
        # 当且仅当 stack 中只剩下一个元素且为 # 时返回 True.
        return True if len(stack) == 1 and stack[0] == "#" else False

源代码文件在 这里 。
©本文首发于 何睿的博客 ,欢迎转载,转载需保留 文章来源 ,作者信息和本声明.

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43377.html

相关文章

  • leetcode331. Verify Preorder Serialization of a Bi

    摘要:如果我们从右往左看先序遍历,就知道后两个节点如果遇到第三个节点,则该节点就应当是这两个节点的父节点。如果在遍历的过程中根节点数量小于,则说明这棵树有问题。而如果遍历结束之后,剩下的根节点数不等于,也说明这个先序遍历存在问题。 题目要求 One way to serialize a binary tree is to use pre-order traversal. When we en...

    weapon 评论0 收藏0
  • Verify Preorder Serialization of a Binary Tree

    摘要:令,那么从累加会一直保持正,最后为。从左往右比较好理解,因为总是总到左再到右,的总是的,所以一定是保持。注意从开始,因为没有。 Verify Preorder Serialization of a Binary Tree 题目链接:https://leetcode.com/problems... recursion,用个全局的index: public class Solution {...

    melody_lql 评论0 收藏0
  • leetcode449. Serialize and Deserialize BST

    摘要:题目要求将二叉搜索树序列化和反序列化,序列化是指将树用字符串的形式表示,反序列化是指将字符串形式的树还原成原来的样子。假如二叉搜索树的节点较多,该算法将会占用大量的额外空间。 题目要求 Serialization is the process of converting a data structure or object into a sequence of bits so that...

    Honwhy 评论0 收藏0
  • [Leetcode] Verify Preorder Sequence in Binary Sear

    摘要:如果继续降序,说明又向左走了,这样等到下次向右走得时候也要再次更新最小值。这样,序列无效的条件就是违反了这个最小值的限定。我们同样可以用本题的方法解,不过是从数组的后面向前面遍历,因为在后面了。栈的增长方向也是从高向低了。 Verify Preorder Sequence in Binary Search Tree Given an array of numbers, verify ...

    未东兴 评论0 收藏0
  • Serialize and Deserialize Binary Tree & BST

    摘要:思路理论上说所有遍历的方法都可以。但是为了使和的过程都尽量最简单,是不错的选择。用作为分隔符,来表示。复杂度代码思路这道题和之前不同,一般的树变成了,而且要求是。还是可以用,还是需要分隔符,但是就不需要保存了。 297. Serialize and Deserialize Binary Tree Serialization is the process of converting a...

    eccozhou 评论0 收藏0

发表评论

0条评论

张巨伟

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<