# Middle-题目51：331. Verify Preorder Serialization of a Binary Tree

86人阅读 评论(0)

Middle-题目51：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.

public class Solution {
public boolean isValidSerialization(String preorder) {
String[] nodes = preorder.split(",");
Stack<String> stack = new Stack<String>();
for(String str : nodes) {
stack.push(str);
int size = stack.size();
while(size > 2 && stack.get(size-1).equals("#") && stack.get(size-2).equals("#") && !stack.get(size-3).equals("#")) {
stack.pop();
stack.pop();
stack.pop();
stack.push("#");
size = stack.size();
}
}
return stack.size() == 1 && stack.peek().equals("#");
}
}

public class Solution {
public boolean isValidSerialization(String preorder) {
int len = preorder.length();
int count = 0;
for(int i=len-1; i>=0; i--){
char tmp = preorder.charAt(i);
if(tmp == ','){
continue;
}else if(tmp == '#'){
count++;
}else if(tmp != ',' && tmp != '#' && i!=0 && preorder.charAt(i-1)!=','){
continue;
}else{
if(count<2){
return false;
}else{
count--;
}
}
}
return count==1;
}
}

Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56775次
• 积分：3211
• 等级：
• 排名：第10678名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论