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

class Solution {
public:
bool isValidSerialization(string preorder) {
stack<char> stk;
bool isNum = false;
preorder.push_back(','); // dummy tail for(auto c: preorder){
if(c == '#'){
// absorb: search for pattern `#, number` backward
while(!stk.empty() && stk.top() == '#'){
stk.pop(); // pop `#`
if(stk.empty() || stk.top() == '#') return false; // pattern `#,#,#`
stk.pop(); // pop `number`
}
stk.push('#'); // replace `number` with `#` since it has been fully explored/validated
}else if(c == ','){
if(isNum) stk.push('n'); // indicate this is a number instead of using the real number
isNum = false;
}else{
isNum = true;
}
} return stk.size() == && stk.top() == '#';
}
};

2. 不用栈

class Solution {
public:
bool isValidSerialization(string preorder) {
string& s = preorder;
while (s.size() >= ) {
bool find_pattern = false;
for (int i = s.size()-; i>= ; i--) {
if (s[i] == '#' && s[i-] == '#' && s[i-] != '#') {
find_pattern = true;
int j = i--;
/* find the start place of pattern */
while (j > && s[j] != ',') j--;
s.replace(j+, i-j, "#"); /* replace s[j+1, i] to "#" */
break; /* start a trun search from the end */
}
}
if (!find_pattern) break;
} /* boundary: empty tree */
return (s.size() == && s[] == '#');
}
};

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

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. 过千万、亿条数据的mysql表更新 mysql 线程状态

    分段更新 UPDATE question SET `status`=1 WHERE status!=1 LIMIT 3000;UPDATE answer SET `status`=1 WHERE st ...

  2. Introduction to Structured Data json的2种形式 JAVA解析JSON数据 - JsonArray JsonObject

    https://developers.google.com/search/docs/guides/intro-structured-data Structured data refers to kin ...

  3. 第二次作业(WordCount)

    1 Github项目地址:https://gitee.com/DamonGetup/WordCount/tree/master 2 对程序设计语言源文件统计字符数.单词数.行数,统计结果以指定格式输出 ...

  4. rbac - 初识

    一.rbac 权限组件 1 项目与应用 一个项目,可以有多个应用 一个应用,可以在多个项目下 前提:应用是组件!! 2 什么是权限? 一个包含正则表达式url就是一个权限 who what how - ...

  5. Team Formation---zoj3870(异或)

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5518 题意就是有n个数,如果满足a^b > MAX(a, b) ...

  6. UEM用户行为了如指掌!

    “千呼万唤始出来”,万众期待的UEM正式与宝宝们见面啦~~~ 今天很多人来问小编,Web咋不见了,表急,Web并没有消失,而是重磅升级为UEM啦!!! 什么是UEM呢?UEM全称User Experi ...

  7. MDF文件损坏,如何恢复?(未解决)

    MDF文件损坏,如何恢复?MDF附加失败,数据库附加失败 1.附加时 2.用替换法设置后重建日志 (其实已经删掉日志了,确保操作之前没有日志,但是运行 alter database [test] Re ...

  8. python 面向对象 类 __doc__

    用来打印类的描述信息 class A1(object): '''类的描述信息''' print(A1.__doc__) # 类的描述信息

  9. cookie、session、sessionid ,jsessionid 的区别

    本文是转载虫师博客的文章http://www.cnblogs.com/fnng/archive/2012/08/14/2637279.html cookie.session.sessionid 与js ...

  10. Thread的六中状态

    线程共有6种状态:在某一时刻只能是这6种状态之一.这些状态由Thread.State这个枚举类型表示,并且可以通过getState()方法获得当前线程具体的状态类型. NEW:至今尚未启动的线程的状态 ...