Leetcode 331. Verify Preorder Serialization of a Binary Tree
Given a string of comma-separated values, verify whether it represents a correct preorder serialization of a binary tree. A null node is represented by a #
.
For example, the string “9,3,4,#,#,1,#,#,2,#,6,#,#” corresponds to the following binary tree:
9
/ \
3 2
/ \ \
4 1 6
Each comma-separated value indicates a node, and #
represents a null node.
To solve this problem, we can simulate the process of forming the binary tree using a counter for slots. Each non-null node uses one slot but creates two new slots, whereas a null node uses one slot without creating any new slot.
#include <iostream>
#include <sstream>
bool isValidSerialization(std::string preorder) {
std::istringstream iss(preorder);
std::string node;
int slots = 1;
while (std::getline(iss, node, ',')) {
slots--; // one slot is taken by the current node
// if at any point slots are less than 0, the serialization is invalid
if (slots < 0) {
return false;
}
// non-null node produces two additional slots
if (node != "#") {
slots += 2;
}
}
// slots should be zero if the serialization is valid
return slots == 0;
}
int main() {
std::string preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#";
std::cout << (isValidSerialization(preorder) ? "Valid" : "Invalid") << std::endl;
std::string preorder_invalid = "1,#";
std::cout << (isValidSerialization(preorder_invalid) ? "Valid" : "Invalid") << std::endl;
return 0;
}
slots
, node
) are used, and we do not use any additional space proportional to the input size.This solution efficiently verifies the preorder serialization string of a binary tree with a linear time complexity and constant space complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?