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

题目描述

根据二叉树的前序遍历和中序遍历的结果,重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
在这里插入图片描述

解题思路

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

/**
 * 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;
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_43469680/article/details/107815374