Tree-----重建树(根据中序和前序,中序和后序)

1.根据中序和前序

原题目


public class Solution {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0) {
            return null;
        }
        return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    public TreeNode build(int[] preorder, int leftP, int rightP, int[] inorder, int leftI, int rightI) {
        if (leftP > rightP || leftI > rightI) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[leftP]);
        int indexInInOrder = findRootIndexInOrder(inorder, leftI, rightI, root.val);
        int offset = indexInInOrder - leftI - 1;
        TreeNode left = build(preorder, leftP + 1, leftP + 1 + offset, inorder, leftI, indexInInOrder - 1);
        TreeNode right = build(preorder, leftP + offset + 2, rightP, inorder, indexInInOrder + 1, rightI);
        root.left = left;
        root.right = right;
        return root;
    }

    public int findRootIndexInOrder(int[] inorder, int left, int right, int target) {
        int result = 0;
        for (int i = left; i <= right; i++) {
            if (inorder[i] == target) {
                result = i;
                break;
            }
        }
        return result;
    }

}

offset很重要,一步到位

2.根据中序和后序

public class Solution {

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || inorder.length == 0 || postorder == null || postorder.length == 0) {
            return null;
        }
        return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    public TreeNode build(int[] inorder, int leftI, int rightI, int[] postorder, int leftP, int rightP) {
        if (leftI > rightI || leftP > rightP) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[rightP]);
        int indexInInOrder = findRootIndexInOrder(inorder, leftI, rightI, root.val);
        int offset = indexInInOrder - 1 - leftI;
        TreeNode left = build(inorder, leftI, indexInInOrder - 1, postorder, leftP, leftP + offset);
        TreeNode right = build(inorder, indexInInOrder + 1, rightI, postorder, leftP + offset + 1, rightP - 1);
        root.left = left;
        root.right = right;
        return root;
    }

    public int findRootIndexInOrder(int[] inorder, int left, int right, int target) {
        int result = 0;
        for (int i = left; i <= right; i++) {
            if (inorder[i] == target) {
                result = i;
                break;
            }
        }
        return result;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值