Java Recursive Solution, 23ms, beat 90%


  • 0
    F
    public TreeNode str2tree(String s) {
    	if (s == null || s.length() == 0)
    		return null;
    
    	int left_left = s.indexOf('(');
    	if (left_left < 0) {
    		return new TreeNode(Integer.valueOf(s));
    	}
    	TreeNode root = new TreeNode(Integer.valueOf(s.substring(0, left_left)));
    	int left_right = getRight(s, left_left);
    	root.left = str2tree(s.substring(left_left + 1, left_right));
    
    	int right_left = s.indexOf('(', left_right);
    	if (right_left > 0) {
    		int right_right = getRight(s, right_left);
    		root.right = str2tree(s.substring(right_left + 1, right_right));
    	}
    	return root;
    }
    
    private int getRight(String s, int i) {
    	int count = 1;
    	while (i < s.length() && count > 0) {
    		i++;
    		if (s.charAt(i) == '(')
    			count++;
    		if (s.charAt(i) == ')')
    			count--;
    	}
    	return i;
    }

Log in to reply
 

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