Recursive Solution beats 100% - 11ms


  • 0
    N
    int index=0;
        public TreeNode util(String s){
            if(index<s.length()){
                boolean flag = false; int value = 0;
                //get the value first, if negative change to -
                if(s.charAt(index)=='-'){ flag = true; index++; }
                while(index<s.length() && s.charAt(index)!='(' && s.charAt(index)!=')'){
                    value = value*10 + s.charAt(index)-'0';
                    index++;
                }
                if(flag) value = -value;
                
                TreeNode root = new TreeNode(value);
                if(index<s.length() && s.charAt(index)=='(' && s.charAt(index-1)!=')'){
                    index++;
                    root.left = util(s);
                }
                if(index<s.length() && s.charAt(index)=='(' && s.charAt(index-1)==')'){
                    index++;
                    root.right = util(s);
                }
                if(index<s.length() && s.charAt(index)==')')
                    index++;
    
                return root;
            }
            return null;
        }
        public TreeNode str2tree(String s) {
           return util(s);
        }
    
    1. get the value and check for negative
    2. with braces condition check go left or right
    3. when braces is ')', that node is done, returns back

Log in to reply
 

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