Thursday, November 20, 2014

Construct Binary Tree from preOrder and inOrder Leetcode

Similarly, copy the solution from postOrder and inOrder.

public TreeNode buildTree(int[] preorder, int[] inorder) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(preorder == null || inorder == null) return null;
        if(preorder.length == 0 || inorder.length == 0) return null;
        return build (preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}

        public TreeNode build(int[] preorder, int start1, int end1, int[] inorder, int start2,
int end2) {
        if(start1 > end1 || start2 > end2) return null;
int current = preorder[start1];
TreeNode currRoot = new TreeNode(current);
        int k = start2;
        for(; k < inorder.length; k++)
        if(inorder[k] == current) break;
        currRoot.left = build(preorder, start1+1, start1-start2+k, inorder, start2, k-1);
        currRoot.right = build(preorder, start1-start2+k+1,end1, inorder, k+1, end2);
        return currRoot;
    }

No comments:

Post a Comment