Neat JAVA solution: pretty easy to read


  • 6
    G
    public class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if (preorder.length == 0) {
            	return null;
            }
            return buildTreeHelper(preorder, inorder, 0, preorder.length-1, 0, preorder.length-1);
        }
        
        public TreeNode buildTreeHelper(int[] preorder, int[] inorder, int ps, int pe, int is, int ie) {
            if (ps > pe || is > ie) {
            	return null;
            }
            TreeNode root = new TreeNode(preorder[ps]);
            if (ps == pe) {
            	return root;
            }
            int index = 0;
            for (int i=is; i<=ie; i++) {
                if (root.val == inorder[i]) {
                    index = i;
                    break;
                }
            }
            root.left = buildTreeHelper(preorder, inorder, ps+1, ps+index-is, is, index-1);
            root.right = buildTreeHelper(preorder, inorder, ps+index-is+1, pe, index+1, ie);
            return root;
        }
    }

  • 0
    F

    Maybe, it's better to think about the preorder== null or inorder == null .


  • 0
    S

    There's wrong answer of you code


Log in to reply
 

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