-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathrecover-a-tree-from-preorder-traversal.cpp
67 lines (63 loc) · 1.7 KB
/
recover-a-tree-from-preorder-traversal.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// iterative stack solution
class Solution {
public:
TreeNode* recoverFromPreorder(string S) {
int i = 0;
vector<TreeNode *> stack;
while (i < S.length()) {
int j = S.find_first_not_of("-", i);
int level = j - i;
i = j;
while (stack.size() > level) {
stack.pop_back();
}
j = S.find_first_of("-", i);
auto node = new TreeNode(stoi(S.substr(i, j - i)));
i = j;
if (!stack.empty()) {
if (!stack.back()->left) {
stack.back()->left = node;
} else{
stack.back()->right = node;
}
}
stack.emplace_back(node);
}
return stack.front();
}
};
// Time: O(n)
// Space: O(h)
// recursive solution
class Solution2 {
public:
TreeNode* recoverFromPreorder(string S) {
int i = 0;
return recoverFromPreorderHelper(S, 0, &i);
}
private:
TreeNode* recoverFromPreorderHelper(const string& S, int level, int *i) {
int j = S.find_first_not_of("-", *i);
if (level != j - *i) {
return nullptr;
}
*i = j;
j = S.find_first_of("-", *i);
auto node = new TreeNode(stoi(S.substr(*i, j - *i)));
*i = j;
node->left = recoverFromPreorderHelper(S, level + 1, i);
node->right = recoverFromPreorderHelper(S, level + 1, i);
return node;
}
};