-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsoln.cpp
49 lines (49 loc) · 1.46 KB
/
soln.cpp
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* recoverFromPreorder(string S) {
int pre = -1;
vector<pair<TreeNode *, int>> stk;
TreeNode * root = nullptr;
int lo = 0, n = S.length();
while (lo < n) {
int depth = 0;
while (lo < n && S[lo] == '-') {
++depth;
++lo;
}
int val = 0;
while (lo < n && isdigit(S[lo])) {
val = val * 10 + S[lo] - '0';
++lo;
}
// cout << depth << " " << val << endl;
TreeNode * node = new TreeNode(val);
if (root == nullptr) {
root = node;
}
if (depth > pre) {
if (!stk.empty()) stk.back().first->left = node;
} else if (depth == pre) {
stk[stk.size() - 2].first->right = node;
// cout << stk[stk.size() - 2].first->val << "right" << node->val << endl;
} else {
while (!stk.empty() && stk.back().second >= depth) {
stk.pop_back();
}
stk.back().first->right = node;
}
stk.emplace_back(node, depth);
pre = depth;
}
return root;
}
};