One way to serialize a binary tree is to use preorder traversal. When we encounter a non-empty node, we can record the value of this node. If it is an empty node, we can use a tag value record, such as #.
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #
For example, the above binary tree can be serialized into the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents an empty node.
Given a comma-separated sequence, verify that it is the correct preorder serialization of the binary tree. Write a feasible algorithm without reconstructing the tree.
Each comma-separated character is either an integer or a'#' representing a null pointer.
You can think that the input format is always valid, for example, it will never contain two consecutive commas, such as "1,3".
Example 1:
Input: "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: true
Design idea: The first-order queue is the root node, the left node, and the right node Loop traversal, each node has a left and right node (+2), which can also be called the root or left or right node (-1).
代码:
public static boolean isValidSerialization(String preorder) {
String[]a=preorder.split(",");
if(a[0].equals("#")&&a.length==1) {
return true;
}
if(a[0].equals("#")&&a.length!=1) {
return false;
}
int count=1;//记录结点未知的叶子节点数
for(int i=0;i<a.length;i++){
count--;
if(count<0) {
return false;
}
if(!a[i].equals("#")) {
count+=2;
}
}
return count==0;
}