Sponsored
Sponsored
The idea is to track available slots in the binary tree. Initially, we start with one slot for the root. For each node, we consume a slot. If the node is non-null, it adds two more slots (one for each child). A null node ('#') does not add any slots. The binary tree is valid if, at the end of processing all nodes, all slots are exactly filled (i.e., zero slots remaining).
Time Complexity: O(n), where n is the length of the preorder string, as we are iterating through the nodes once.
Space Complexity: O(1), with no additional data structures used.
1#include <stdio.h>
2#include <string.h>
3#include <stdbool.h>
4
5bool isValidSerialization(char * preorder) {
6 int slots = 1;
7 for (char *ptr = strtok(preorder, ","); ptr; ptr = strtok(NULL, ",")) {
8 slots--;
9 if (slots < 0) {
10 return false;
11 }
12 if (strcmp(ptr, "#") != 0) {
13 slots += 2;
14 }
15 }
16 return slots == 0;
17}
18
19int main() {
20 char preorder[] = "9,3,4,#,#,1,#,#,2,#,6,#,#";
21 printf("%s\n", isValidSerialization(preorder) ? "true" : "false");
22 return 0;
23}
The code uses strtok to tokenize the input string by commas. It starts with 1 available slot and decrements the slot count for each node. Non-null nodes (integers) add two slots, while null nodes ('#') simply use up a slot. If slots go negative at any point, the serialization is invalid. Finally, check all slots are used up.
This approach involves simulating a stack-based tree traversal. The idea is to treat each "open bracket" as requiring nodes and each "close bracket" as completing them. We aim to manage the state of openings and closures using integers, representing how many nodes are expected at any point in the traversal.
Time Complexity: O(n), parsing each node once.
Space Complexity: O(1), with only integer variables used for tracking.
This Java code implements a simulation using a running variable 'diff'. This acts similarly to managing a stack size.