106. Construct Binary Tree from Inorder and Postorder Traversal

public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return buildTree(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
	}
    private TreeNode buildTree(int[] inorder, int l1, int r1, int[] postorder, int l2, int r2) {
        if(l1>r1||l2>r2)
            return null;
        int idx=r1;
        while(inorder[idx]!=postorder[r2])
            idx--;
        TreeNode node=new TreeNode(postorder[r2]);
        node.left=buildTree(inorder, l1, idx-1, postorder, l2, l2+idx-1-l1);
        node.right=buildTree(inorder, idx+1, r1, postorder, l2+idx-l1, r2-1);
        return node;
    }
}

  

posted @ 2017-09-29 12:30  Weiyu Wang  阅读(105)  评论(0编辑  收藏  举报