【LeetCode】331. Verify Preorder Serialization of a Binary Tree 解题报告(Python)

标签: LeetCode


题目地址:https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/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 #.

  1. _9_
  2. / \
  3. 3 2
  4. / \ / \
  5. 4 1 # 6
  6. / \ / \ / \
  7. # # # # # #

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”.

  1. Example 1:
  2. "9,3,4,#,#,1,#,#,2,#,6,#,#"
  3. Return true
  4. Example 2:
  5. "1,#"
  6. Return false
  7. Example 3:
  8. "9,#,#,1"
  9. Return false

题目大意

给了一个先序遍历,判断能不能构成合法的二叉树。这个字符串中,#表示空节点。

解题方法

我们的思路应该是这样的:判断一个二叉树是否合法的情况,那么应该是个递归或者循环问题。那么解决问题的思路是从顶部向下分析还是从底下向顶部分析呢?正确的结果应该是从二叉树的底部向上进行分析,因为我们可以通过#号判断是否是空节点,然后判断最底下的叶子节点是否含有两个空孩子的方式,循环向上解决这个问题。

所以这个题的思路就很明了了:用一个栈,从字符串的左侧向右依次进栈,如果满足栈的后三位是数字,#,#的模式时,说明可以构成合法的叶子节点,把这个叶子节点换成#号,代表空节点,然后继续遍历。最后应该只剩下一个#,那么就是一个合法的二叉树。

  1. 如:”9,3,4,#,#,1,#,#,2,#,6,#,#” 遇到x # #的时候,就把它变为 #
  2. 模拟一遍过程:
  3. 9,3,4,#,# => 9,3,# 继续读
  4. 9,3,#,1,#,# => 9,3,#,# => 9,# 继续读
  5. 9,#2,#,6,#,# => 9,#,2,#,# => 9,#,# => #
  1. class Solution(object):
  2. def isValidSerialization(self, preorder):
  3. """
  4. :type preorder: str
  5. :rtype: bool
  6. """
  7. stack = []
  8. for node in preorder.split(','):
  9. stack.append(node)
  10. while len(stack) >= 3 and stack[-1] == stack[-2] == '#' and stack[-3] != '#':
  11. stack.pop(), stack.pop(), stack.pop()
  12. stack.append('#')
  13. return len(stack) == 1 and stack.pop() == '#'

方法二:

这个方法还是第一次使用:看出度和入度的差。

我们知道一个树(甚至图),所有节点的入度之和等于出度之和。那么可以根据这个条件进行有效性的判断。

对于二叉树,我们把空的地方也作为叶子节点(如题目中的#),那么有

  1. 所有的非空节点提供2个出度和1个入度(根除外)
  2. 所有的空节点但提供0个出度和1个入度

我们在遍历的时候,计算diff = outdegree – indegree. 当一个节点出现的时候,diff – 1,因为它提供一个入度;当节点不是#的时候,diff+2(提供两个出度) 如果序列式合法的,那么遍历过程中diff >=0 且最后结果为0.

这里解释一下为什么diff的初始化为1.因为,我们加入一个非空节点时,都会先减去一个入度,再加上两个出度。但是由于根节点没有父节点,所以其入度为0,出度为2.因此diff初始化为1,是为了再加入根节点的时候,先减去一个入度,再加上两个出度,正好应该是2.

  1. class Solution(object):
  2. def isValidSerialization(self, preorder):
  3. """
  4. :type preorder: str
  5. :rtype: bool
  6. """
  7. nodes = preorder.split(',')
  8. diff = 1
  9. for node in nodes:
  10. diff -= 1
  11. if diff < 0:
  12. return False
  13. if node != '#':
  14. diff += 2
  15. return diff == 0

参考:https://www.hrwhisper.me/leetcode-verify-preorder-serialization-of-a-binary-tree/

日期

2018 年 3 月 13 日

【LeetCode】331. Verify Preorder Serialization of a Binary Tree 解题报告(Python)的更多相关文章

  1. leetcode 331. Verify Preorder Serialization of a Binary Tree

    传送门 331. Verify Preorder Serialization of a Binary Tree My Submissions QuestionEditorial Solution To ...

  2. 【LeetCode】Verify Preorder Serialization of a Binary Tree(331)

    1. Description One way to serialize a binary tree is to use pre-order traversal. When we encounter a ...

  3. LeetCode OJ 331. 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, ...

  4. [LeetCode] 331. Verify Preorder Serialization of a Binary Tree_Medium tag: stack

    One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, ...

  5. 【leetcode】331. 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 ...

  6. 331. 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, ...

  7. 331. 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, ...

  8. 331 Verify Preorder Serialization of a Binary Tree 验证二叉树的前序序列化

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

  9. LeetCode 331. 验证二叉树的前序序列化(Verify Preorder Serialization of a Binary Tree) 27

    331. 验证二叉树的前序序列化 331. Verify Preorder Serialization of a Binary Tree 题目描述 每日一算法2019/5/30Day 27LeetCo ...

随机推荐

  1. Telink BLE MESH PWM波的小结

    本本针对Telink BLE MESH SDK  灯控的使用进行说明. 1.调整灯光的频率 默认情况下 SDK PWM波的频率是 600HZ的,有时我们需要将它调整频率,例如调整为4K,只需要更改参数 ...

  2. Go语言缺陷

    我为什么放弃Go语言 目录(?)[+] 我为什么放弃Go语言 有好几次,当我想起来的时候,总是会问自己:我为什么要放弃Go语言?这个决定是正确的吗?是明智和理性的吗?其实我一直在认真思考这个问题. 开 ...

  3. sed 修改文件

    总结 正确的修改进文件命令(替换文件内容):sed -i "s#machangwei#mcw#g" mcw.txt 正确的修改追加进文件命令(追加文件内容):sed -i &quo ...

  4. 生产调优3 HDFS-多目录配置

    目录 HDFS-多目录配置 NameNode多目录配置 1.修改hdfs-site.xml 2.格式化NameNode DataNode多目录配置(重要) 1.修改hdfs-site.xml 2.测试 ...

  5. 【Android】No Android SDK found(mac)+ 真机调试

     [1]No Android SDK found 如果没下载SDK,可以去google官方下载 如果因为上网问题,这里提供两个网址,有人整理好了,这里先谢谢他们,下面两个择其一下载 http://to ...

  6. Default Assignment Operator and References

    We have discussed assignment operator overloading for dynamically allocated resources here . This is ...

  7. size_type 和 size_t 的区别

    标准库string里面有个函数size,用来返回字符串中的字符个数,具体用法如下:string st("The expense of spirit\n");cout << ...

  8. 【Linux】【Services】【Project】Haproxy Keepalived Postfix实现邮件网关Cluster

    1. 简介: 1.1. 背景:公司使用exchange服务器作为邮件服务器,但是使用Postfix作为邮件网关实现病毒检测,内容过滤,反垃圾邮件等功能.原来的架构非常简单,只有两台机器,一个负责进公司 ...

  9. NoSQL之Redis学习笔记

    一.NoSQL与Redis 1.什么是NoSQL? NoSQL=Not Only SQL ,泛指非关系型数据库.随着互联网的兴起,传统的关系型数据库已经暴露了很多问题,NoSQL数据库的产生就是为了解 ...

  10. 【VSCode】检测到 #include 错误。请更新 includePath。已为此翻译单元(C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\i686-

    win+r 运行cmd 输入"gcc -v -E -x c -"获取mingw路径: 我的: #include "..." search starts here ...