forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct-binary-tree-from-string.cpp
More file actions
43 lines (40 loc) · 1000 Bytes
/
construct-binary-tree-from-string.cpp
File metadata and controls
43 lines (40 loc) · 1000 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
32
33
34
35
36
37
38
39
40
41
42
43
// 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) {}
* };
*/
class Solution {
public:
TreeNode* str2tree(string s) {
int i = 0;
return s.empty() ? nullptr : str2treeHelper(s, &i);
}
private:
TreeNode* str2treeHelper(const string& s, int *i) {
auto start = *i;
if (s[*i] == '-') {
++(*i);
}
while (*i < s.length() && isdigit(s[*i])) {
++(*i);
}
auto node = new TreeNode(stoi(s.substr(start, *i - start)));
if (*i < s.length() && s[*i] == '(') {
++(*i);
node->left = str2treeHelper(s, i);
++(*i);
}
if (*i < s.length() && s[*i] == '(') {
++(*i);
node->right = str2treeHelper(s, i);
++(*i);
}
return node;
}
};