-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVerifyPreorderSerializationofaBinaryTree.java
41 lines (37 loc) · 1.29 KB
/
VerifyPreorderSerializationofaBinaryTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public boolean isValidSerialization(String preorder) {
String[] strArray = preorder.split(",");
Stack<String> nodeStack = new Stack<String>();
int size = strArray.length;
if(size == 0){
return false;
} else if(size == 1 && strArray[0].equals("#")){
return true;
}
nodeStack.push(strArray[0]);
for(int i = 1; i != size; i ++){
if(strArray[i].equals("#")){
if(nodeStack.empty()){
return false;
} else if(!nodeStack.peek().equals("#")){
nodeStack.push(strArray[i]);
} else{
while(!nodeStack.empty() && nodeStack.peek().equals("#")){
nodeStack.pop();
if(nodeStack.empty()){
return false;
}
nodeStack.pop();
}
if(nodeStack.empty() && i == size - 1){
return true;
}
nodeStack.push("#");
}
} else{
nodeStack.push(strArray[i]);
}
}
return nodeStack.empty();
}
}