###### 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;
};

#### [leetcode] Verify Preorder Serialization of a Binary Tree

2016-03-08 21:13:20

#### leetcode 331 ：Verify Preorder Serialization of a Binary Tree：简单题

2016-03-09 17:26:05

#### 【LeetCode】331. Verify Preorder Serialization of a Binary Tree

2016-03-17 10:36:09

#### LeetCode 331. Verify Preorder Serialization of a Binary Tree

2016-03-23 15:55:55

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

2016-03-04 11:36:19

#### leetcode_c++：栈： Verify Preorder Serialization of a Binary Tree（331 )

2016-07-23 15:45:28

#### [leetcode] 255. Verify Preorder Sequence in Binary Search Tree 解题报告

2016-03-19 06:12:50

#### [LeetCode255]Verify Preorder Sequence in Binary Search Tree

2015-11-25 11:53:39

#### Given preorder and inorder traversal of a tree, construct the binary tree.

2014-12-04 23:07:11

#### 【LeetCode】144 . Binary Tree Preorder Traversal 解题报告

2016-05-22 23:53:41

## 不良信息举报

331. Verify Preorder Serialization of a Binary Tree