重建二叉树

题目链接:

  重建二叉树_牛客题霸_牛客网 (nowcoder.com)

   

  根据 前序遍历 和 中序遍历重建二叉树,返回根节点

 

import java.util.*;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    Map<Integer,Integer> map = new HashMap<>();// 存储中序遍历,方便确定前序遍历得到的根节点在中序遍历中 的位置
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        
        for(int i=0;i<pre.length;i++){
            map.put(vin[i],i);
        }
        return reConstructTree(pre,0,0,pre.length-1);
    }
    // 递归找到根节点
    // preL : 前序第一个节点 preR:前序最后一个节点 vinL中序遍历第一个节点
    public TreeNode reConstructTree(int[] pre,int preL,int vinL,int preR){
        //  出口
        if(preL>preR){
            return null;
        }
        //  返回
        TreeNode root = new TreeNode(pre[preL]);
        // 计算左子树长度
        // 根节点在右子树的位置 
        int vIndex = map.get(root.val);
        int leftSize = vIndex - vinL;
        // 找左子树的根
        TreeNode left = reConstructTree(pre,preL+1,vinL,preL+leftSize);
        
        // 找右子树的根
        TreeNode right = reConstructTree(pre,preL+leftSize+1,vIndex+1,preR);
        
        root.left = left;
        root.right = right;
        
        return root;
    }
}

  

 

posted @ 2022-08-29 11:29  yky_xukai的胡思乱想  阅读(23)  评论(0)    收藏  举报