classSolution{public:TreeNode*str2tree(strings){if(s.empty())returnnullptr;inti=0;returnstr2tree(s,i);}private:TreeNode*str2tree(conststring&s,int&i){constintstart=i;// Start index of valif(s[i]=='-')++i;while(i<s.length()&&isdigit(s[i]))++i;constintval=stoi(s.substr(start,i-start));TreeNode*root=newTreeNode(val);// Left childif(i<s.length()&&s[i]=='('){++i;// '('root->left=str2tree(s,i);++i;// ')'}// Right childif(i<s.length()&&s[i]=='('){++i;// '('root->right=str2tree(s,i);++i;// ')'}returnroot;}};
classSolution{publicTreeNodestr2tree(Strings){if(s.isEmpty())returnnull;returnhelper(s);}privateinti=0;privateTreeNodehelper(finalStrings){finalintstart=i;// Start index of valif(s.charAt(i)=='-')++i;while(i<s.length()&&Character.isDigit(s.charAt(i)))++i;finalintval=Integer.parseInt(s.substring(start,i));TreeNoderoot=newTreeNode(val);// Left childif(i<s.length()&&s.charAt(i)=='('){++i;// '('root.left=helper(s);++i;// ')'}// Right childif(i<s.length()&&s.charAt(i)=='('){++i;// '('root.right=helper(s);++i;// ')'}returnroot;}}