Java Solution


  • 0
    public TreeNode str2tree(String s) {
        if (s.length() == 0) return null; 
        
        int sub = s.indexOf('('); 
        int val = sub != -1 ? Integer.parseInt(s.substring(0, sub)) : Integer.parseInt(s);
        //Construct the current node
        TreeNode root = new TreeNode(val); 
        if (sub != -1) {
            String[] children = parseString(s.substring(sub));  
            root.left = str2tree(children[0]); //left subtree
            root.right = str2tree(children[1]); //right subtree
        }
        return root; 
    }   
    
    String[] parseString(String str) {
        int open = 1, len = str.length(), leftClose = 0;
        for (leftClose = 1; leftClose < len; leftClose++) {
            if (str.charAt(leftClose) == '(') open++; 
            if (str.charAt(leftClose) == ')') open--; 
            if (open == 0) break; 
        }
        String leftString = str.substring(1, leftClose); // get the left subtree string
        String rightString = ""; // get the right subtree string
        if (leftClose != len - 1)
            rightString = str.substring(leftClose + 2, len - 1); // strip off the "()"
        
        return new String[]{leftString, rightString}; 
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.