[LeetCode] Construct Binary Tree from String

536. Construct Binary Tree from String

You need to construct a binary tree from a string consisting of parenthesis and integers.

The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root’s value and a pair of parenthesis contains a child binary tree with the same structure.

You always start to construct the left child node of the parent first if it exists.

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
/**
* 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 {
void buildNode(string &s, int &pos, TreeNode* cur) {
if(pos >= s.length() || s[pos] == ')'){
pos++;
return;
}

int flag = s[pos] == '-' ? -1 : 1, val = 0;
if(flag == -1)
pos++;
for(; pos < s.length(); pos++) {
if('0' <= s[pos] && s[pos] <= '9')
val = (val<<3) + (val<<1) + (s[pos] & 0b1111);
else
break;
}
cur->val = flag * val;
if(s[pos] == ')') {
pos++;
return;
} else if(s[pos] == '(') {
pos++;
cur->left = new TreeNode();
buildNode(s, pos, cur->left);
}

if(s[pos] == ')') {
pos++;
return;
} else if(s[pos] == '(') {
pos++;
cur->right = new TreeNode();
buildNode(s, pos, cur->right);
}

pos++;
return;
}
public:
TreeNode* str2tree(string s) {
if(s.length() == 0)
return nullptr;
TreeNode* root = new TreeNode();
int pos = 0;
buildNode(s,pos,root);
return root;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/15/PS/LeetCode/construct-binary-tree-from-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.