The problem asks you to verify whether a given preorder serialization of a binary tree is valid. The serialization is provided as a string, with each node's value separated by commas. Null nodes are represented by the character #
.
For example, the string "9,3,4,#,#,1,#,#,2,#,6,#,#"
represents the preorder traversal of a binary tree, where each node or #
is visited in preorder (root, left, right).
#
for null).#
separated by commas.class Solution:
def isValidSerialization(self, preorder: str) -> bool:
slots = 1
for node in preorder.split(','):
slots -= 1
if slots < 0:
return False
if node != '#':
slots += 2
return slots == 0
class Solution {
public:
bool isValidSerialization(string preorder) {
int slots = 1;
int n = preorder.size();
for (int i = 0; i < n;) {
if (slots == 0) return false;
if (preorder[i] == '#') {
slots--;
i++;
} else {
// Parse number
while (i < n && preorder[i] != ',') i++;
slots++; // slots = slots - 1 + 2
}
// Skip comma
while (i < n && preorder[i] == ',') i++;
}
return slots == 0;
}
};
class Solution {
public boolean isValidSerialization(String preorder) {
int slots = 1;
String[] nodes = preorder.split(",");
for (String node : nodes) {
slots--;
if (slots < 0) return false;
if (!node.equals("#")) slots += 2;
}
return slots == 0;
}
}
var isValidSerialization = function(preorder) {
let slots = 1;
const nodes = preorder.split(',');
for (let node of nodes) {
slots--;
if (slots < 0) return false;
if (node !== '#') slots += 2;
}
return slots === 0;
};
When first encountering this problem, you might try to reconstruct the binary tree explicitly while parsing the string. This approach would involve building tree nodes and checking if the structure is valid, but this is unnecessary and inefficient.
Instead, we can focus on the properties of preorder traversal and serialization. Each non-null node provides two "slots" for its children, while each node (including nulls) consumes one slot. If, at any point, we run out of slots before finishing the traversal, or if there are leftover slots at the end, the serialization is invalid.
The key insight is recognizing that we can validate the structure by counting available slots as we process each node, rather than reconstructing the tree itself.
#
), add 2 slots (since it can have two children).This approach is efficient because it requires only a single pass through the input and no extra data structures.
Let's walk through the input "9,3,4,#,#,1,#,#,2,#,6,#,#"
step by step:
At the end, slots = 0, so the serialization is valid.
The key to solving this problem efficiently is understanding the relationship between nodes and available child "slots" in a binary tree. By counting slots as we process each node, we can validate the serialization in a single pass without reconstructing the tree. This elegant approach is both time and space efficient, and highlights how careful reasoning about binary tree properties can simplify complex problems.