-
Notifications
You must be signed in to change notification settings - Fork 28
/
Construct_Binary_Tree_from_String.cpp
53 lines (53 loc) · 1.48 KB
/
Construct_Binary_Tree_from_String.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
/**
* 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) {
stack<TreeNode*> nodeStack;
int n = (int)s.length();
if(n == 0) return nullptr;
int i = 0;
while(i < n) {
if(isdigit(s[i]) or s[i] == '-') {
bool positive = true;
if(s[i] == '-') {
positive = false;
i++;
}
int value = s[i] - '0';
while(i + 1 < n and isdigit(s[i + 1])) {
value = value * 10 + (s[i + 1] - '0');
i++;
}
if(!positive) {
value = -value;
}
TreeNode* node = new TreeNode(value);
if(!nodeStack.empty()) {
TreeNode* parent = nodeStack.top();
if(!parent->left) {
parent->left = node;
} else {
parent->right = node;
}
}
nodeStack.push(node);
}
else if(s[i] == ')') {
nodeStack.pop();
}
else if(s[i] == '(') {
// nothing
}
i++;
}
return nodeStack.top();
}
};