评论区看来的思路:
把‘#’看成叶子节点,利用叶子节点数 = 非叶子节点数 + 1的特点
class Solution {
public boolean isValidSerialization(String preorder) {
int nodeCount = 1, leafCount = 0;
for(char c : preorder.toCharArray()){
if(leafCount > nodeCount - leafCount) return false;
if(c == ',') nodeCount++;
if(c == '#') leafCount++;
}
return (leafCount - (nodeCount - leafCount)) == 1;
}
}