从前序与中序遍历序列构造二叉树——疯狂递归吧

二叉树的遍历是递归来实现,两样反向构建二叉树,也是用递归实现。原题链接

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

二叉树的基础和三种遍历方式,请看这篇文章:前序遍历、中序遍历和后序遍历
直接上代码,用代码解释更明了。


    Map<Integer, Integer> map = new HashMap<Integer, Integer>(); // 全局变量
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = preorder.length;
        for(int i = 0; i < n; i++){
            map.put(inorder[i], i);   // 根节点在中序遍历中的位置,存储在map中
        }
        return buildTree(preorder, 0, n-1, inorder, 0, n-1);
    }
    /**
    * preLeft 前序遍历的开始位置
    * preRight 前序遍历的结束位置
    * inLeft 中序遍历的开始位置
    * inRight 中序遍历的结束位置
    **/
    private TreeNode buildTree(int[] preorder, int preLeft, int preRight, int[] inorder, int inLeft, int inRight){
        if(preLeft > preRight) return null;
        TreeNode root = new TreeNode(preorder[preLeft]); // 前序遍历的第一个元素就是根节点
        int point = map.get(preorder[preLeft]); // 找到根节点在中序遍历中的位置
        int leftCount = point - inLeft; // 左子树元素的个数
        root.left = buildTree(preorder, preLeft + 1, preLeft + leftCount, inorder, inLeft, point -1);
        root.right = buildTree(preorder, preLeft + leftCount + 1, preRight, inorder, point + 1, inRight);
        return root;

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值