331. Verify Preorder Serialization of a Binary Tree

Stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public boolean isValidSerialization(String preorder) {
// root -> left -> right

String[] nodes = preorder.split(",");
List<String> nodeList = new ArrayList<>(nodes.length);
for (String node : nodes) {
if (node.equals("#")) {
while (nodeList.size() >= 2 && nodeList.get(nodeList.size() - 1).equals("#") && !nodeList.get(nodeList.size() - 2).equals("#")) {
// 模式:3##,即叶子节点,此时消去该叶子节点
nodeList.remove(nodeList.size() - 1);
nodeList.remove(nodeList.size() - 1);
}
nodeList.add("#");
} else {
nodeList.add(node);
}
}

return nodeList.size() == 1 && nodeList.get(0).equals("#");
}
}

Degree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean isValidSerialization(String preorder) {
// 所有节点的入度和与出度和应该相等
String[] array = preorder.split(",");

int degreeDiff = 1; // 给 root 预留的入度
for (String s : array) {
degreeDiff--; // 减去一个入度
if (degreeDiff < 0) { // 在遍历节点过程中,出度减入度应该大于等于 0
return false;
}
if (!s.equals("#")) {
degreeDiff += 2; // 非空节点具有两个出度
}
}

return degreeDiff == 0;
}
}

References

331. Verify Preorder Serialization of a Binary Tree