public class Solution {
public TreeNode str2tree(String s) {
Stack<TreeNode> stack = new Stack<>();
for(int i = 0, j = i; i < s.length(); i++, j = i){
char c = s.charAt(i);
if(c == ')') stack.pop();
else if(c >= '0' && c <= '9'  c == ''){
while(i + 1 < s.length() && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') i++;
TreeNode currentNode = new TreeNode(Integer.valueOf(s.substring(j, i + 1)));
if(!stack.isEmpty()){
TreeNode parent = stack.peek();
if(parent.left != null) parent.right = currentNode;
else parent.left = currentNode;
}
stack.push(currentNode);
}
}
return stack.isEmpty() ? null : stack.peek();
}
}
Java stack solution



Good solution! I have the same idea in C++.
class Solution { public: TreeNode* str2tree(string s) { if (s == "") return nullptr; stack<TreeNode*> sk; int n = s.size(), i = 0; while(i < n && s[i] != '(' && s[i] != ')') i++; TreeNode *root = new TreeNode(stoi(s.substr(0, i))); sk.push(root); while (i < n) { if (s[i++] == ')') sk.pop(); else { int j = i; while(i < n && s[i] != '(' && s[i] != ')') i++; TreeNode *p = new TreeNode(stoi(s.substr(j, ij))); if (sk.top()>left) sk.top()>right = p; else sk.top()>left = p; sk.push(p); } } return root; } };

@soham6 There is no such situation. Pay attention to: An empty tree is represented by "" instead of "()".