1. 程式人生 > >106. Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

postorder bin while post private true light length 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;
    }
}

  

106. Construct Binary Tree from Inorder and Postorder Traversal