My Java Solution


  • 0
    W
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder, 0, inorder, 0, preorder.length);
    }
    
    TreeNode build(int[] preorder, int preStart, int[] inorder, int inStart, int len) {
        if (len == 0) {
            return null;
        }
    
        int rootVal = preorder[preStart];
        TreeNode root = new TreeNode(rootVal);
        int i;
        for (i = 0; i < len; i++) {
            if (inorder[inStart + i] == rootVal) {
                break;
            }
        }
        root.left = build(preorder, preStart + 1, inorder, inStart, i);
        root.right = build(preorder, preStart + i + 1, inorder, inStart + i + 1, len - i - 1);
    
        return root;
    }
    

Log in to reply
 

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