LeetCode

Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Java

public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int inStart = 0;
        int inEnd = inorder.length - 1;
        int postStart = 0;
        int postEnd = postorder.length - 1;

        return buildTree(inStart, inEnd, inorder, postStart, postEnd, postorder);
    }

    private TreeNode buildTree(int inStart, int inEnd, int[] inorder, int postStart, int postEnd, int[] postorder) {
        if(inStart > inEnd || postStart > postEnd) {
            return null;
        }

        int rootValue = postorder[postEnd];
        TreeNode root = new TreeNode(rootValue);

        int index = 0;

        for(int i = inStart; i < inorder.length; i++) {
            if(inorder[i] == rootValue) {
                index = i;
                break;
            }
        }
        root.left = buildTree(inStart, index - 1, inorder, postStart, postStart + (index - 1) - inStart, postorder);
        root.right = buildTree(index + 1, inEnd, inorder, postStart + index - inStart, postEnd - 1, postorder);
        return root;
    }
}