536. Construct Binary Tree from String
https://www.lintcode.com/problem/construct-binary-tree-from-string/description
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param s: a string
* @return: a root of this tree
*/
int pos = 0;
TreeNode * str2tree(string &s) {
TreeNode *cur = nullptr;
int num = 0, sign = 1, lbc = 0;
while (pos < s.size()) {
const auto c = s[pos++];
if (c == '-') {
sign = -1;
} else if (c >= '0' && c <= '9') {
num = num * 10 + (c - '0');
} else if (c == '(') {
if (cur == nullptr) cur = new TreeNode(sign * num);
++lbc;
if (lbc == 1) cur->left = str2tree(s);
else cur->right = str2tree(s);
} else {
if (lbc == 0) {
cur = new TreeNode(sign * num);
}
break;
}
}
return cur;
}
};Last updated