JAVA分治土办法--but effective


  • 0
    G
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode str2tree(String s) {
            if(s.equals("")){
                return null;
            }
            int len = s.length();
            
            int startIndex=0;
            String rs = "";
            
            while(startIndex<len && (Character.isDigit(s.charAt(startIndex)) || s.charAt(startIndex)=='-')){
                rs += s.charAt(startIndex);
                startIndex++;
            }
            
            int rootval = Integer.valueOf(rs);
            TreeNode root = new TreeNode(rootval);
            
            if(startIndex==len){
                return root;
            }
            
            int endIndex=startIndex;
            int count=0;
            for(;endIndex<len;endIndex++){
                if(s.charAt(endIndex)=='('){
                    count++;
                }else if (s.charAt(endIndex)==')'){
                    count--;
                }
                
                if(count==0){
                    break;
                }
            }
            
           
            
            root.left = str2tree(s.substring(startIndex+1,endIndex));
            
            if(endIndex+1==len){
                return root;
            }
    
            int count1 =0;
            endIndex++;
            int endIndex1 = endIndex;
            
            for(;endIndex1<len;endIndex1++){
                if(s.charAt(endIndex1)=='('){
                    count1++;
                }else if (s.charAt(endIndex1)==')'){
                    count1--;
                }
                
                if(count1==0){
                    break;
                }
            }
    
            root.right = str2tree(s.substring(endIndex+1,endIndex1));
            return root;
        }
    }
    

Log in to reply
 

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