Java Recursive Solution, similar to 394. Decode String


  • 0
    G
    int index = 0;
    
    public TreeNode str2tree(String s) {
        if(s.isEmpty()) {
            return null;
        }
        
        TreeNode root = new TreeNode(0);
        int num = 0;
        int sign = 1;
        
        while(index < s.length() && s.charAt(index) != ')') {
            char ch = s.charAt(index);
            if(ch == '-') {
                sign = -1;
                index++;
            } else if(ch >= '0' && ch <= '9') {
                num = num * 10 + ch - '0';
                index++;
            } else if(ch == '(') {
                // skip '('
                index++;
                // process node
                TreeNode child = str2tree(s);
                // skip ')'
                index++;
                
                if(root.left == null) {
                    root.left = child;
                } else {
                    root.right = child;
                }
            }
        }
        
        root.val = sign * num;
        return root;
    }

Log in to reply
 

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