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) {
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("#")) { 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; for (String s : array) { degreeDiff--; if (degreeDiff < 0) { return false; } if (!s.equals("#")) { degreeDiff += 2; } }
return degreeDiff == 0; } }
|
References
331. Verify Preorder Serialization of a Binary Tree