前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【剑指Offer】7. 重建二叉树

【剑指Offer】7. 重建二叉树

作者头像
瑞新
发布2020-12-07 14:19:55
2120
发布2020-12-07 14:19:55
举报

题目描述

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

在这里插入图片描述
在这里插入图片描述

解题思路

前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。

代码语言:javascript
复制
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    // 缓存中序遍历数组每个值对应的索引
    private Map<Integer,Integer> indexOfInOder = new HashMap<>();

    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        for(int i=0; i<in.length; i++) {
            indexOfInOder.put(in[i], i);
        }
        return reConstructBinaryTree(pre, 0, pre.length-1, 0);
    }
    // 建立树-递归左右子树
    private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int inL){
        if(preL > preR)
            return null;
        
        TreeNode root = new TreeNode(pre[preL]);
        int indexInRoot = indexOfInOder.get(root.val);
        int size = indexInRoot - inL; // 中序根节点两边距离
        root.left = reConstructBinaryTree(pre, preL+1, preL+size, inL);
        root.right = reConstructBinaryTree(pre, preL+size+1, preR, inL+size+1);
        return root;
    }


}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-08-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档