Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created October 21, 2017 19:37
/**
* 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) {
s = "(" + s + ")";
int len = s.size();
return s2T(s, 0, len - 1);
}
private:
TreeNode* s2T(string s, int lo, int hi)
{
if(lo + 1 > hi - 1)return nullptr;
TreeNode* node = nullptr;
int num = 0, i = lo + 1;
bool isNeg = s[i] == '-'? true: false;
if(isNeg)++i;
while(i < hi && isdigit(s[i]))
num = num * 10 + (s[i++] - '0');
node = new TreeNode(isNeg? -num: num);
if(i == hi)return node;//leaf node
int count = 0, j = i;
while(j <= hi)
{
if(s[j] == '(')++count;
else if(s[j] == ')') --count;
if(!count)break;
++j;
}
node->left = s2T(s, i, j);
node->right = s2T(s, j + 1, hi - 1);
return node;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment