原题链接:331. Verify Preorder Serialization of a Binary Tree
【思路】
本题考查字符串的操作和树的基本概念。注意题目要求构造一个完整的树,所有叶子节点都要以#结束,也就是"9,#,#"满足要求,二"9,#"和”9"不满足。本题中在字符串前面加了一个逗号,目的是在每次遇到逗号之后,判断下一个字符为空或数字(有可能不止一位,如"9,#,98,#,#"):
public boolean isValidSerialization(String preorder) {
int curCount = 0;
int curShouldCount = 1;
int nextShouldCount = 0;
int i = 0;
preorder = "," + preorder;
for (; i < preorder.length(); i++) {
if (preorder.charAt(i) == ',') {
if (preorder.charAt(i + 1) != '#')
nextShouldCount += 2;
if (++curCount == curShouldCount) {
if (nextShouldCount == 0) break;
curShouldCount = nextShouldCount;
nextShouldCount = 0;
curCount = 0;
}
}
}
return i + 2 == preorder.length() && curCount == curShouldCount;
}
150 / 150
test cases passed. Runtime: 5 ms Your runtime beats 98.04% of javasubmissions.
欢迎优化!