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

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

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

已知前序中序 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;
    }    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值