One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'
.
For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#"
, where '#'
represents a null node.
Given a string of comma-separated values preorder
, return true
if it is a correct preorder traversal serialization of a binary tree.
It is guaranteed that each comma-separated value in the string must be either an integer or a character '#'
representing null pointer.
You may assume that the input format is always valid.
- For example, it could never contain two consecutive commas, such as
"1,,3"
.
Note: You are not allowed to reconstruct the tree.
Example 1:
Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" Output: true
Example 2:
Input: preorder = "1,#" Output: false
Example 3:
Input: preorder = "9,#,#,1" Output: false
Constraints:
1 <= preorder.length <= 104
preorder
consist of integers in the range[0, 100]
and'#'
separated by commas','
.
题目链接:https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/
题目大意:给一个二叉树先序遍历序列化后的字符串,在不能构造二叉树的情况下判断此序列化结果是否正确
题目分析:先序遍历是中左右的顺序,可按照顺序将序列化的值压栈(空为-1),出栈的规则为必须在栈顶找到两个连续的-1,当某个值出栈后,需要将该值变为-1,相当于其父节点的孩子节点此时为空,如果最终栈中只剩一个-1,则为合法状态
3ms,时间击败91%
class Solution {
public boolean isValidSerialization(String preorder) {
char[] s = preorder.toCharArray();
int n = s.length, top = 0;
int[] stk = new int[n + 1];
if (n > 0 && s[n - 1] != '#') {
return false;
}
int num = 0;
for (int i = 0; i < n; i++) {
if (s[i] == ',') {
if(s[i - 1] != '#') {
stk[++top] = num;
}
num = 0;
} else if (s[i] == '#') {
stk[++top] = -1;
} else {
num = num * 10 + (s[i] - '0');
}
}
while (top > 1) {
if (top > 1 && stk[top] == -1 && stk[top - 1] == -1) {
top -= 2;
} else {
break;
}
int tmp = top;
while (tmp > 1 && stk[tmp] == -1) {
tmp--;
}
if (stk[tmp] == -1) {
return false;
}
stk[tmp] = -1;
}
return top == 1 && stk[top] == -1;
}
}
更简单的做法是直接根据出入度判断,遇到数字度数+2(左右孩子),遍历到每个位置度数-1