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 <sstream>
2#include <string>
3#include <iostream>
4using namespace std;
5
6bool isValidSerialization(string preorder) {
7 int slots = 1;
8 stringstream ss(preorder);
9 string node;
10 while (getline(ss, node, ',')) {
11 slots--;
12 if (slots < 0) return false;
13 if (node != "#") slots += 2;
14 }
15 return slots == 0;
16}
17
18int main() {
19 string preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#";
20 cout << (isValidSerialization(preorder) ? "true" : "false");
21 return 0;
22}
Using a stringstream to parse the preorder traversal string. The logic is similar to the C implementation. We begin with one slot, decrement by one for each node. If it's a non-null node, we increment slots by 2.
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 C code uses strtok for splitting and maintains a count 'diff' (similar to slots) decrementing for nodes and adjusting according to whether nodes are null or not.