题目:牛客网

解题思路:

不需要辅助函数,简单易懂

后序遍历容器的最后一个数是根节点,中序遍历的根节点左边是左子树,右边是右子树,

后序遍历左子树节点值相邻,右子树节点值也相邻。由后序遍历最后一个值将中序遍历分成

左右两部分,再由这两部分的size将后序遍历分成左右两部分,递归即可

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public static TreeNode buildTree(int[] inorder, int[] postorder) {
		if(inorder.length==0 || postorder.length == 0)
            return null;
		return solve(inorder , 0, inorder.length-1, postorder, 0, postorder.length-1 );
	}
	public static TreeNode solve(int[] inorder,int in_start, int in_end, int[] postorder, int post_start, int post_end) {
        if(in_start>in_end||post_start>post_end)
            return null;
        TreeNode root = new TreeNode(postorder[post_end]);
        int index=0;
        for(int i=0;i<=in_end;i++){
            if(inorder[i]==postorder[post_end]){
                index=i;
            }
        }
        root.left = solve(inorder , in_start, index-1, postorder, post_start, post_start+index- in_start-1 );
        root.right = solve(inorder , index+1, in_end , postorder, post_start+index- in_start, post_end-1);
        return root;
    }
}