-
Notifications
You must be signed in to change notification settings - Fork 387
Expand file tree
/
Copy paths1.cpp
More file actions
31 lines (31 loc) · 867 Bytes
/
s1.cpp
File metadata and controls
31 lines (31 loc) · 867 Bytes
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
// OJ: https://leetcode.com/problems/construct-binary-tree-from-string
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(logN)
class Solution {
private:
TreeNode* rec(string &s, int begin, int end, TreeNode *p) {
if (begin >= end) return NULL;
int i = begin;
while (i < end && s[i] == '-' || isdigit(s[i])) ++i;
TreeNode *node = new TreeNode(stoi(s.substr(begin, i - begin)));
if (p) {
if (!p->left) p->left = node;
else p->right = node;
}
if ((begin = i) < end) {
int leftCnt = 1;
for (i = begin + 1; leftCnt && i < end; ++i) {
if (s[i] == '(') ++leftCnt;
else if (s[i] == ')') --leftCnt;
}
rec(s, begin + 1, i - 1, node);
rec(s, i + 1, end - 1, node);
}
return node;
}
public:
TreeNode* str2tree(string s) {
return rec(s, 0, s.size(), NULL);
}
};