7. 重建二叉树

剑指offer 07 重建二叉树

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

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

限制:

0 < = 节 点 个 数 < = 5000 0 <= 节点个数 <= 5000 0<=<=5000

注意:本题与主站 105 题重复:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

前置知识:如有重复数字,则前序和中序无法确定一颗二叉树,因为不知道前序序列中的重复数字对应中序序列中同一重复数字的哪一个,导致无法判断当前前序序列中节点的左右节点。

解题思路

前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。然后分别对左右子树递归地求解。

  • 先用HashMapinorder序列存好(key:节点的val value:节点在序列中的索引位置),然后根据HashMap找到根节点在inorder序列中的位置。
  • 根节点的valHashMap中对应的值就是根节点在inorder序列中的位置。
  • 然后可以根据中序中根节点左右两边的结点个数,递归的建立树了。
    在这里插入图片描述

Java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
    
    
        if(preorder==null || preorder.length==0) return null;//preorder.length==0的话,inorder.length肯定也为0,所以只判断一个即可
        HashMap<Integer ,Integer> hashmap = new HashMap<>();
        for(int i = 0;i<inorder.length;i++){
    
    //将中序的信息存入HashMap,方便后面根据根节点分割左右子树
            hashmap.put(inorder[i],i);
        }
        return dfs(preorder,0,preorder.length-1,0,hashmap);
    }
    
    //pl即preorder left,即前序数组的左边界,pr即前序数组的右边界,同理il即中序的左边界
    public TreeNode dfs(int[] preorder,int pl,int pr,int il,HashMap<Integer ,Integer> hashmap){
    
    
        if(pl>pr) return null;//递归终止条件,前序数组中没有元素了
        TreeNode curRoot = new TreeNode(preorder[pl]);//当次递归的根节点
        int k = hashmap.get(curRoot.val);//当前根节点在中序数组中的索引
        curRoot.left = dfs(preorder,pl+1,pl+(k-il),il,hashmap); //k-il即当前递归栈中序中左子树的结点个数
        curRoot.right = dfs(preorder,pl+(k-il)+1,pr,k+1,hashmap);
        return curRoot;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/YouMing_Li/article/details/114238737