-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1028.cpp
More file actions
29 lines (28 loc) · 826 Bytes
/
Copy path1028.cpp
File metadata and controls
29 lines (28 loc) · 826 Bytes
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
class Solution {
public:
TreeNode *recoverFromPreorder(string S) {
int pos = 0, back = 0;
return Construct(0, S, pos, back);
}
TreeNode *Construct(int level, string &S, int &pos, int &back) {
if (pos >= S.size())
return nullptr;
string str;
int val = 0;
while (pos < S.size() && S[pos] != '-')
str += S[pos++];
val = stoi(str);
auto curr = new TreeNode(val);
int len = 0;
while (pos < S.size() && S[pos] == '-')
++len, ++pos;
if (len != level + 1) {
back = len;
return curr;
}
curr->left = Construct(level + 1, S, pos, back);
if (level == back - 1)
curr->right = Construct(level + 1, S, pos, back);
return curr;
}
};