本题是给一个字符串,让你判断其是否是一个二叉树序列,其中空节点用#表示。例如
_9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # # # #
For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#"
可以看出,#总比数字个数多1.而且总以#结尾。我们先用一个s数组存储分割出来的字符串,先判断最后一个是不是#。
随后,我们对除了最后一个字符的所有字符串进行统计,使用count这个变量记录。如果是数字,加一,如果是字符,减一,而且由于数字总在#之前,
所以在循环进行时,一旦count小于0,返回false。
最后判断count,是0,返回true,否则返回false;
代码如下:
class Solution {
public boolean isValidSerialization(String preorder) {
String[] c = preorder.split(",");
int l = c.length;
if(!c[l-1].equals("#"))
return false;
int count =0;
for (int i= 0; i< c.length-1;i ++) {
if(c[i].equals("#"))
count--;
else
count++;
if(count<0)
return false;
}
return count==0;
}
}