从前序与中序遍历序列构造二叉树

从前序与中序遍历序列构造二叉树1

给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。

package tree;

import java.util.HashMap;
import java.util.Map;


public class BuildTree {
    /**
     * 从前序与中序遍历序列构造二叉树
     *
     * @param preorder 前序遍历
     * @param inorder  中序遍历
     * @return 二叉树根结点
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
    
        int preLen = preorder.length;
        int inLen = inorder.length;

        if (preLen != inLen) {
            throw new RuntimeException("Incorrect input data.");
        }
        // 构造哈希映射,快速定位根节点
        Map<Integer, Integer> rootIndexMap = new HashMap<>(preLen);
        for (int i = 0; i < inLen; i++) {
            rootIndexMap.put(inorder[i], i);
        }

        return buildTree(preorder, 0, preLen - 1, rootIndexMap, 0, inLen - 1);
    }

    /**
     *  前序遍历:   根        左             (左子树结束位置)             右
     *          preLeft   preLeft+1    pIndex - inLeft + preLeft     preRight
     *  中序遍历:   左         根          右
     *           inLeft     pIndex     inRight
     *  左子树个数 = pIndex - inLeft =(左子树结束位置)- preLeft
     */
    public TreeNode buildTree(int[] preorder, int preLeft, int preRight,
                              Map<Integer, Integer> rootIndexMap, int inLeft, int inRight) {
        if (preLeft > preRight || inLeft > inRight) {
            return null;
        }

        int rootVal = preorder[preLeft];
        // 先把根节点建立出来
        TreeNode root = new TreeNode(rootVal);
        int pIndex = rootIndexMap.get(rootVal);
        root.left = buildTree(preorder, preLeft + 1, pIndex - inLeft + preLeft,
                rootIndexMap, inLeft, pIndex - 1);
        root.right = buildTree(preorder, pIndex - inLeft + preLeft + 1, preRight,
                rootIndexMap, pIndex + 1, inRight);

        return root;
    }
}

根据前序中序遍历序列中子树节点数量相等计算各个序列中左右子树的边界。
在这里插入图片描述



  1. LC105. 从前序与中序遍历序列构造二叉树 ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

椰子zii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值