public static boolean isValidSerialization(String preorder) {
if(preorder == null || preorder.length() == 0) {
return false;
}else {
Stack<String> stack = new Stack<String>();
String[] str = preorder.split(",");
if(str.length == 2) {
return false;
}
int i = 0;
boolean is = true;
for(i = 0; i < str.length; i++) {
if(str[i].equals("#")) {
String pc1 = "#";
String pc2 = "";
if(!stack.isEmpty()) {
pc2 = stack.peek();
}else {
if(i == str.length) {
stack.push("#");
break;
}else {
is =false;
break;
}
}
while(pc1.equals("#") && pc1 == pc2) {
stack.pop();
if(stack.isEmpty()) {
is = false;
break;
}
String cc = stack.peek();
if(cc.equals("#")) {
is = false;
break;
}else {
stack.pop();
pc1 = "#";
if(!stack.isEmpty()) {
pc2 = stack.peek();
}else {
pc2 = "";
break;
}
}
}
if(is) {
stack.push(pc1);
}else {
break;
}
}else {
stack.push(str[i]);
}
}
if(!is) {
return false;
}else {
if(stack.isEmpty()) {
return false;
}else{
String pc = stack.peek();
stack.pop();
if(pc.equals("#") && stack.isEmpty()) {
return true;
}else {
return false;
}
}
}
}
}
331. Verify Preorder Serialization of a Binary Tree
最新推荐文章于 2024-10-13 15:10:00 发布