-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1028.cpp
More file actions
39 lines (39 loc) · 1.22 KB
/
1028.cpp
File metadata and controls
39 lines (39 loc) · 1.22 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* _recoverFromPreorder(string traversal, int& index, int depth) {
if (index >= traversal.size()) return nullptr;
int currDepth = 0;
while (traversal[index] == '-') {
index++;
currDepth++;
}
if (currDepth < depth) {
index -= currDepth;
return nullptr;
}
int val = 0;
while (isdigit(traversal[index])) {
val = val * 10 + traversal[index] - '0';
index++;
}
TreeNode* node = new TreeNode(val);
node->left = _recoverFromPreorder(traversal, index, depth + 1);
node->right = _recoverFromPreorder(traversal, index, depth + 1);
return node;
}
TreeNode* recoverFromPreorder(string traversal) {
int index = 0;
return _recoverFromPreorder(traversal, index, 0);
}
};