Created
October 21, 2017 19:37
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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