Stack的应用——Verify Preorder Serialization of a Binary Tree
来源:互联网 发布:json转java实体对象 编辑:程序博客网 时间:2024/06/07 03:07
问题描述:
给定一个用逗号分隔的字符串,验证它是否是二叉树的正确的前序遍历序列。 找到一个不用重建树的算法。字符串中的每两个逗号之间必须是整数或表示空指针的字符'#'。
解题思路:
Example 1:"9,3,4,#,#,1,#,#,2,#,6,#,#"
Return true
根据例子,可以得到一种简单的思路:先用vector<string>存储每两个逗号之间的内容。遍历这个容器,如果出现“1,#,#”这种情况,则可以将其用“#”代替,不断重复这个过程。如果最后剩下的是“#”,则返回TRUE,否则返回FALSE。
源代码如下:
class Solution {
public:
bool isValidSerialization(string preorder) {
vector<string> preorder0;
string temp="";
for(int i=0;i<preorder.size();i++)
{
if(preorder[i]!=',')
temp+=preorder[i];
else
{
preorder0.push_back(temp);
temp="";
}
}
preorder0.push_back(temp);
stack<string> stk;
for(int i=0;i<preorder0.size();i++)
{
if(preorder0[i]!="#")
stk.push(preorder0[i]);
else
{
if(stk.empty()) stk.push(preorder0[i]);
else if(!stk.empty()&&stk.top()!="#") stk.push(preorder0[i]);
else
{
while(!stk.empty()&&stk.top()=="#")
{
stk.pop();
if(stk.empty()) return false;
stk.pop();
}
stk.push("#");
}
}
}
return stk.size()==1&&stk.top()=="#";
}
};
public:
bool isValidSerialization(string preorder) {
vector<string> preorder0;
string temp="";
for(int i=0;i<preorder.size();i++)
{
if(preorder[i]!=',')
temp+=preorder[i];
else
{
preorder0.push_back(temp);
temp="";
}
}
preorder0.push_back(temp);
stack<string> stk;
for(int i=0;i<preorder0.size();i++)
{
if(preorder0[i]!="#")
stk.push(preorder0[i]);
else
{
if(stk.empty()) stk.push(preorder0[i]);
else if(!stk.empty()&&stk.top()!="#") stk.push(preorder0[i]);
else
{
while(!stk.empty()&&stk.top()=="#")
{
stk.pop();
if(stk.empty()) return false;
stk.pop();
}
stk.push("#");
}
}
}
return stk.size()==1&&stk.top()=="#";
}
};
0 0
- Stack的应用——Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- leetcode——331——Verify Preorder Serialization of a Binary Tree
- LeetCode题解——Verify Preorder Serialization of a Binary Tree
- LeetCode刷题(C++)——Verify Preorder Serialization of a Binary Tree(Medium)
- leetcode Verify Preorder Serialization of a Binary Tree
- 331. Verify Preorder Serialization of a Binary Tree
- Leetcode: Verify Preorder Serialization of a Binary Tree
- LeetCode Verify Preorder Serialization of a Binary Tree
- JavaScript中对象的一些基本用法
- PHP操作Postgresql类
- 有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。 给定二叉树的根结点root,请返回打印结果,
- 292. Nim Game
- preparing launch delegate问题
- Stack的应用——Verify Preorder Serialization of a Binary Tree
- 【Leetcode】21. Merge Two Sorted Lists
- Html,css学习总结(二)
- 文章标题
- Maven将jar包放入本地库
- 数据结构——树(2)一般树转二叉树Java实现
- 任务调度系统-任务依赖的设计
- C语言程序现代设计方法---第七章:基本类型
- sdutacm-删数问题