递归应用-根据遍历顺序构造二叉树

已知前序遍历和中序遍历,可以构造唯一二叉树
同样,已知后序和中序遍历,可以构造唯一二叉树

但是已知前序和后序,并不能构造唯一二叉树,因为对于单个子节点无法确定到底是左子树还是右子树

已知前序中序 Leetcode

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTree(preorder, 0, preorder.length, inorder, 0, inorder.length);
    }

    private TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
        if(preorder == null || preEnd==preStart) return null;

        int v = preorder[preStart];

        TreeNode root = new TreeNode(v);

        int index = inStart;
        while (inorder[index]!=v) ++index;

        int leftCount = index - inStart;

        root.left = buildTree(preorder, preStart+1, preStart+1+leftCount, inorder, inStart, index);
        root.right = buildTree(preorder,preStart+1+leftCount, preEnd, inorder, index+1, inEnd);
        return root;
    }    

已知后序中序 Leetcode

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return buildTree(inorder, 0, inorder.length, postorder, 0, postorder.length);
    }

   privateTreeNode buildTree(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
        if(postorder == null || postStart==postEnd) return null;

        int v = postorder[postEnd-1];

        TreeNode root = new TreeNode(v);

        int index = inStart;
        while (inorder[index]!=v) ++index;

        int leftCount = index - inStart;

        root.left = buildTree(inorder, inStart, index, postorder, postStart, postStart+leftCount);
        root.right = buildTree(inorder,index+1, inEnd, postorder, postStart+leftCount, postEnd-1);
        return root;
    }    

你可能感兴趣的:(Algorithm,算法,leetcode,二叉树)