106.从中序后序遍历序列构造二叉树

58 阅读1分钟

106.从中序后序遍历序列构造二叉树

image.png

image.png

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length == 0 || postorder.length == 0) return null;
        //根节点的值是后序数组最后一个节点的值
        TreeNode root = new TreeNode(postorder[postorder.length - 1]);
        for(int i = 0; i < inorder.length; i++){
            if(postorder[postorder.length - 1] == inorder[i]){
                //中序遍历的左子树和右子树,copyOfRange是左闭右开的
                int [] inorder_left = Arrays.copyOfRange(inorder,0,i);
                int [] inorder_right = Arrays.copyOfRange(inorder,i + 1,inorder.length);
                //后序遍历的左子树和右子树
                int [] postorder_left = Arrays.copyOfRange(postorder,0,i);
                int [] postorder_right = Arrays.copyOfRange(postorder,i,postorder.length - 1);
                root.left = buildTree(inorder_left,postorder_left);
                root.right = buildTree(inorder_right,postorder_right);
                break;
            }  
        }
        return root;
    }
}