-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
46 lines (46 loc) · 1.23 KB
/
Solution.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
/**
* 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) {
stack<TreeNode*> st;
int depth = 0;
int num = 0;
for (int i = 0; i < S.length(); ++i) {
if (S[i] == '-') {
depth++;
} else {
num = 10 * num + S[i] - '0';
}
if (i + 1 >= S.length() || (isdigit(S[i]) && S[i + 1] == '-')) {
TreeNode* newNode = new TreeNode(num);
while (st.size() > depth) {
st.pop();
}
if (!st.empty()) {
if (st.top()->left == nullptr) {
st.top()->left = newNode;
} else {
st.top()->right = newNode;
}
}
st.push(newNode);
depth = 0;
num = 0;
}
}
TreeNode* res;
while (!st.empty()) {
res = st.top();
st.pop();
}
return res;
}
};