Similar idea.

class Solution { int pos=-1; public TreeNode str2tree(String s) { pos++; // remove the "(" if (pos>=s.length()) return null; // get the number int start=pos; while (pos<s.length()){ if (s.charAt(pos)=='(' || s.charAt(pos)==')') break; pos++; } TreeNode root=new TreeNode(Integer.parseInt(s.substring(start, pos))); if (pos<s.length() && s.charAt(pos)=='('){ root.left=str2tree(s); if (pos<s.length() && s.charAt(pos)=='(') root.right=str2tree(s); } pos++; // remove ")" return root; } }Construct Binary Tree from String