验证二叉树的前序序列化

class Solution {
public boolean isValidSerialization(String preorder) {
int count = 0;
for(int i = preorder.length() - 1; i >= 0; i--){
if(preorder.charAt(i) == ',') continue;
if(preorder.charAt(i) == '#'){
count++;
}else{
while(i >= 0 && preorder.charAt(i) != ','){
i--;
}
if(count >= 2){
count--;
}else{
return false;
}
}
}
return count == 1;
}
}
class Solution{
public boolean isValidSerialization(String preorder) {
int indegree = 0, outdegree = 0;
String[] split = preorder.split(",");
if(split[0].equals("#")){
return split.length == 1;
}
for (int i = 0; i < split.length; i++) {
if (i == 0) {
outdegree += 2;
} else if (split[i].equals("#")) {
indegree += 1;
} else {
indegree += 1;
outdegree += 2;
}
if (i != split.length - 1 && indegree >= outdegree) {
return false;
}
}
return indegree == outdegree;
}
}
class Solution{
public boolean isValidSerialization(String preorder) {
int inDegree = 0, outDegree = 0;
if(preorder.charAt(0) == '#') {
return preorder.length() == 1;
}
for(int i = 0; i < preorder.length(); i++){
if(i == 0){
outDegree += 2;
i++;
}else if(preorder.charAt(i) == '#'){
inDegree++;
if(i == preorder.length() - 1){
break;
}else{
i++;
}
}else{
while(i < preorder.length() && preorder.charAt(i) != ','){
i++;
}
inDegree++;
outDegree += 2;
}
if(i != preorder.length() - 1 && inDegree >= outDegree) {
return false;
}
}
return inDegree == outDegree;
}
}