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

class Solution {
public:
bool isValidSerialization(string preorder) {
string s = spilt(preorder, ',');
while (!s.empty()){
if (push(s) != 0)
return false;
s = spilt(preorder, ',');
}
return mystack.size()==1 && mystack.top()=='#';
}

private:
string spilt(string& preorder, char ch){
if (preorder.empty())
return preorder;
string s;
int length = preorder.size();
int i;
for (i = 0; i < length; i++){
if (preorder[i] == ch){
s = preorder.substr(0, i);
preorder = preorder.substr(i + 1);
break;
}
}
if (i == length){
s = preorder;
preorder.clear();
}
return s;
}
int push(string s){
if (s.empty())
return 1;
if (s.compare("#") == 0){
if (mystack.empty()){
mystack.push('#');
}
else{
if (mystack.top() == '#'){
mystack.pop();
if (mystack.empty())
return 3;
mystack.pop();
while (!mystack.empty() && mystack.top() == '#'){
mystack.pop();
if (mystack.empty())
return 4;
mystack.pop();
}
mystack.push('#');
}
else{
mystack.push('#');
}
}
}
else{
mystack.push('t');
}
return 0;
}
stack<char> mystack;
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：331. Verify Preorder Serialization of a Binary Tree 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)