536. Construct Binary Tree from String
/**
* 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 pos = 0;
return build(s, pos);
}
private:
TreeNode* build(string s, int& p) {
if (p == s.size()) return nullptr; //pay attention to the base condition! not (!isdigit(s[p])
int val = 0, sign = 1; //pay attention to negative num!!!
if (s[p] == '-') p++, sign = -1;
while (isdigit(s[p])) val = val * 10 + s[p++] - '0';
TreeNode* root = new TreeNode(val*sign);
if (s[p] == '(')
root->left = build(s, ++p);
if (s[p] == '(')
root->right = build(s, ++p);
++p;
return root;
}
};