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

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

Example 2:
"1,#"
Return false

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

1. 栈

  1. class Solution {
  2. public:
  3. bool isValidSerialization(string preorder) {
  4. stack<char> stk;
  5. bool isNum = false;
  6. preorder.push_back(','); // dummy tail
  7.  
  8. for(auto c: preorder){
  9. if(c == '#'){
  10. // absorb: search for pattern `#, number` backward
  11. while(!stk.empty() && stk.top() == '#'){
  12. stk.pop(); // pop `#`
  13. if(stk.empty() || stk.top() == '#') return false; // pattern `#,#,#`
  14. stk.pop(); // pop `number`
  15. }
  16. stk.push('#'); // replace `number` with `#` since it has been fully explored/validated
  17. }else if(c == ','){
  18. if(isNum) stk.push('n'); // indicate this is a number instead of using the real number
  19. isNum = false;
  20. }else{
  21. isNum = true;
  22. }
  23. }
  24.  
  25. return stk.size() == && stk.top() == '#';
  26. }
  27. };

2. 不用栈

  1. class Solution {
  2. public:
  3. bool isValidSerialization(string preorder) {
  4. string& s = preorder;
  5. while (s.size() >= ) {
  6. bool find_pattern = false;
  7. for (int i = s.size()-; i>= ; i--) {
  8. if (s[i] == '#' && s[i-] == '#' && s[i-] != '#') {
  9. find_pattern = true;
  10. int j = i--;
  11. /* find the start place of pattern */
  12. while (j > && s[j] != ',') j--;
  13. s.replace(j+, i-j, "#"); /* replace s[j+1, i] to "#" */
  14. break; /* start a trun search from the end */
  15. }
  16. }
  17. if (!find_pattern) break;
  18. }
  19.  
  20. /* boundary: empty tree */
  21. return (s.size() == && s[] == '#');
  22. }
  23. };

从右向左,若出现(数字,#,#)模式,则替换成一个#。最后若只剩一个#则合法,否则不合法。

331. Verify Preorder Serialization of a Binary Tree -- 判断是否为合法的先序序列的更多相关文章

  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】331. Verify Preorder Serialization of a Binary Tree 解题报告(Python)

    [LeetCode]331. Verify Preorder Serialization of a Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https:/ ...

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

  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 验证二叉树的前序序列化

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

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

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

  8. 【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 ...

  9. [LeetCode] Verify Preorder Serialization of a Binary Tree 验证二叉树的先序序列化

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

随机推荐

  1. Oracle等待事件之db file sequential read/ db file parallel read

    1.产生原因 db file sequential read这个是非常常见的I/O 相关的等待事件.表示发生了与索引扫描相关的等待.意味着I/O 出现了问题,通常表示I/O竞争或者I/O 需求太多. ...

  2. python 的 ord()、 chr()、 unichr() 函数

    一. ord() 函数描述ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返 ...

  3. Redis主从切换

    案例 易车网:http://www.greatops.net/?id=232 redis主从切换:http://www.cnblogs.com/itdragon/p/7932178.htmlhttps ...

  4. android(十五) FTP的两种工作模式

    (一)PORT(主动)方式的连接过程是:客户端向服务器的FTP端口(默认是21)发送连接请求,服务器接受连接,建立一条命令链 当需要传送数据时,客户端在命令链路上用 PORT命令告诉服务器:“我打开了 ...

  5. shell 变量定义技巧总结

    可以多学习和模仿操作系统自带的/etc/init.d/functions函数库脚本的定义思路,多学习Linux系统脚本中的定义,有经验的读者最终应形成一套适合自己的规范和习惯. (1)变量名及变量内容 ...

  6. java-mybaits-00102-mybatis框架原理

    1.mybatis是什么? mybatis是一个持久层的框架,是apache下的顶级项目.是一个不完全的ORM框架. mybatis托管到goolecode下,再后来托管到github下(https: ...

  7. CSU 1642 Problem B[难][前缀和]

    Description 已知两个正整数a和b,求在a与b之间(包含a和b)的所有整数的十进制表示中1出现的次数. Input 多组数据(不超过100000组),每组数据2个整数a,b.(1≤a,b≤1 ...

  8. 小型网站MYSQL问题二:Percona Xtrabackup实现数据库备份和恢复

    1.安装软件仓库(不要问我为什么不用源码安装,好吧,其实我懒.) 1 2 3 4 5 6 7 8 wget https://www.percona.com/downloads/percona-rele ...

  9. Python: 矩阵与线性代数运算

    需要执行矩阵和线性代数运算,比如矩阵乘法.寻找行列式.求解线性方程组等等. 矩阵类似于3.9 小节中数组对象,但是遵循线性代数的计算规则.下面的一个例子展示了矩阵的一些基本特性: >>&g ...

  10. 反射_IsDefined判断方法上有自定义的标签

    在.NET 4.0(当然也包括4.0以前的版本)下,用反射判断某个方法是否运用了自定义Attribute时,可以通过调用MethodInfo的IsDefined()方法进行确认.当然,IsDefine ...