-
Notifications
You must be signed in to change notification settings - Fork 0
/
1028.cpp
52 lines (52 loc) · 1.25 KB
/
1028.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
50
51
52
/**
* 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) {
pos = 0;
return recoverFromPreorder(S,0);
}
private:
int pos;
TreeNode* recoverFromPreorder(const string& S,int deep){
int deep2 = getDeep(S);
if(deep2!=deep){
pos-=deep2;
return NULL;
}
int val = getVal(S);
printf("%d %d\n",deep,val);
TreeNode *tmp = new TreeNode(val);
if(pos>=S.size()) return tmp;
tmp->left = recoverFromPreorder(S,deep+1);
tmp->right = recoverFromPreorder(S,deep+1);
return tmp;
}
int getDeep(const string& S){
int res = 0;
char tmp = S[pos];
while(tmp>'9'||tmp<'0'&&pos<S.size()){
pos++;
tmp = S[pos];
res++;
}
return res;
}
int getVal(const string& S){
int res = 0;
char tmp = S[pos];
while(tmp<='9'&&tmp>='0'&&pos<S.size()){
pos++;
res = 10*res+(tmp-'0');
tmp = S[pos];
}
return res;
}
};