• leetcode 之 Verify Preorder Serialization of a Binary Tree


    题目描述:

    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:
    "9,3,4,#,#,1,#,#,2,#,6,#,#"
    Return true

    Example 2:
    "1,#"
    Return false

    Example 3:
    "9,#,#,1"
    Return false

    即 给定一颗二叉树的前序遍历串,判断这个串是不是合法的。

    分析:1. 前序遍历的即为 根左右遍历,首先访问根节点,然后依次左子树和右子树。

       2. 对于9,3,4,#,#,1,#,#,2,#,6,#,# 这个串来说,6, #,# 一定是一个叶子节点,将其移除后,替换为"#"

       3. 这时串变为: 9,3,4,#,#,1,#,#,2,#,#,继续第二步操作

    使用堆栈保存输入的串,当堆栈后三个元素为 x## 时, 移除这三个元素,并加入#, 最后如果堆栈长度为1 且 值为# ,则返回true

    代码如下:

     1 class Solution(object):
     2     def isValidSerialization(self, preorder):
     3         """
     4         :type preorder: str
     5         :rtype: bool
     6         """
     7         l = len(preorder)
     8         if l == 1 and preorder[0] == "#":
     9             return True
    10         if preorder[0] == "#":
    11             return False
    12         ls = preorder.split(",")
    13         stack = []
    14         for i in ls:
    15             stack.append(i)
    16             while len(stack) >= 3 and stack[-2] == "#" and stack[-1] == "#" and stack[-3] != "#":
    17                 stack.pop()
    18                 stack.pop()
    19                 stack.pop()
    20                 stack.append("#")
    21                 
    22         return len(stack) == 1 and stack[0] == "#"
    ~~~~~
  • 相关阅读:
    linux下文件结束符
    【转】跟我学Kafka之NIO通信机制
    【转】 详解Kafka生产者Producer配置
    【转】项目延期的⑦大因素
    (转)EOSIO开发(三)钱包、账户与账户权限之概念篇
    CentOS里alias命令
    (转)EOSIO开发(一)使用Docker构建本地环境
    Marathon自动扩缩容(marathon-lb-autoscale)
    (转)Springboot日志配置(超详细,推荐)
    Spring Boot下的lombok安装以及使用简介
  • 原文地址:https://www.cnblogs.com/missmzt/p/5564355.html
Copyright © 2020-2023  润新知