331. Verify Preorder Serialization of a Binary Tree
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.
For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node.
Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.
Each comma separated value in the string must be either an integer or a character '#' representing null pointer.
You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".
Example 1:
Input: "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: true
Example 2:
Input: "1,#"
Output: false
Example 3:
Input: "9,#,#,1"
Output: false
preorder字串的最後一個一定是#,且井字號的數量比數字數量多1。
bool isValidSerialization(string preorder) { // time: O(n); space: O(n)
istringstream in(preorder);
vector<string> v;
string buf;
int cnt = 0;
while (getline(in, buf, ',')) v.push_back(buf);
for (int i = 0; i < v.size() - 1; ++i) {
if (v[i] == "#") {
if (cnt == 0) return false;
--cnt;
} else {
++cnt;
}
}
return cnt == 0 && v.back() == "#";
}
bool isValidSerialization(string preorder) { // time: O(n); space: O(1)
istringstream in(preorder);
string buf;
int degree = 1; // the number of # can be accommodated
bool degree_is_zero = false;
while (getline(in, buf, ',')) {
if (degree_is_zero) return false;
if (buf == "#") {
if (--degree == 0) degree_is_zero = true;
} else ++degree;
}
return degree == 0;
}
bool isValidSerialization(string preorder) { // time: O(n); space: O(1)
int capacity = 1; // the number of # can be accommodated
preorder += ",";
for (int i = 0; i < preorder.length(); ++i) {
if (preorder[i] != ',') continue;
if (--capacity < 0) return false;
if (preorder[i - 1] != '#') capacity += 2;
}
return capacity == 0;
}