forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverify-preorder-serialization-of-a-binary-tree.cpp
More file actions
51 lines (45 loc) · 1.11 KB
/
verify-preorder-serialization-of-a-binary-tree.cpp
File metadata and controls
51 lines (45 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Time: O(n)
// Space: O(1)
class Solution {
public:
bool isValidSerialization(string preorder) {
if (preorder.empty()) {
return false;
}
Tokenizer tokens(preorder);
int depth = 0;
int i = 0;
for (; i < tokens.size() && depth >= 0; ++i) {
if (tokens.get_next() == "#") {
--depth;
} else {
++depth;
}
}
return i == tokens.size() && depth < 0;
}
class Tokenizer {
public:
Tokenizer(const string& str) : str_(str), i_(0), cnt_(0) {
size_ = count(str_.cbegin(), str_.cend(), ',') + 1;
}
string get_next() {
string next;
if (cnt_ < size_) {
size_t j = str_.find(",", i_);
next = str_.substr(i_, j - i_);
i_ = j + 1;
++cnt_;
}
return next;
}
size_t size() {
return size_;
}
private:
const string& str_;
size_t size_;
size_t cnt_;
size_t i_;
};
};