剑指offer第七题 重建二叉树(根据前序和中序序列)

问题描述:

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

例如,给出

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

    3
   / \
  9  20
    /  \
   15   7
   

链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof

解题思路:

  按照前序遍历的序列构建二叉树,左右子树可以根据中序遍历判断。

代码实现:

import java.util.HashMap;


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}


//利用原理,先序遍历的第一个节点就是根。在中序遍历中通过根 区分哪些是左子树的,哪些是右子树的
public class text01 {
    static HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();//标记中序遍历
    static int[] pre;//保留的先序遍历

    public static void main(String[] args) {
        int[] pr = {3,9,20,15,7};
        int[] in = {9,3,15,20,7};
        System.out.println(buildTree(pr, in));
    }
    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        TreeNode tree = null;
        pre = preorder;
        for(int i=0; i<preorder.length; i++){
            map.put(inorder[i], i);
        }
        tree = recursive(0, 0, preorder.length-1);
        return tree;
    }

    /**
     * @param pre_root_idx  先序遍历的索引
     * @param left  中序遍历的索引(子树的左边界)
     * @param right 中序遍历的索引(子树的右边界)
     */
    public static TreeNode recursive(int pre_root_idx, int left, int right) {
        if(left > right){
            return null;
        }
        TreeNode root = new TreeNode(pre[pre_root_idx]);
        int idx = map.get(pre[pre_root_idx]);       //在中序遍历中对应的位置
        root.left = recursive(pre_root_idx+1, left, idx-1);
        root.right = recursive(pre_root_idx+(idx-left)+1 ,  idx+1, right);
        return root;
    }

}


提交结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

逍遥自在”

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

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

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

打赏作者

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

抵扣说明:

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

余额充值