331. Verify Preorder Serialization of a Binary Tree
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #Input: "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: trueInput: "1,#"
Output: falseLast updated
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #Input: "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: trueInput: "1,#"
Output: falseLast updated
Input: "9,#,#,1"
Output: falsebool 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;
}