首页 > 其他分享 >重建二叉树

重建二叉树

时间:2022-08-29 11:34:15浏览次数:77  
标签:pre 遍历 TreeNode int 二叉树 root 重建

题目链接:

  重建二叉树_牛客题霸_牛客网 (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;
    }
}

  

 

标签:pre,遍历,TreeNode,int,二叉树,root,重建
From: https://www.cnblogs.com/jsuxk/p/16635325.html

相关文章

  • 110.balanced-binary-tree 平衡二叉树
    获取左右子树的高度,如果左右子树高度差小于等于1,则判断左右子树的左右子树,如此递归下去。classSolution{public:intgetDp(TreeNode*root){if(root......
  • 反转二叉树演练 leetcode |第 6 部分
    反转二叉树演练leetcode|第6部分上一个问题[有效回文演练Leetcode|第5部分上一个问题媒体网](/@nerdhide/valid-palindrome-walkthrough-leetcode-part-5-8......
  • 【重要】LeetCode 662. 二叉树最大宽度
    题目链接注意事项根据满二叉树的节点编号规则:若根节点编号为u,则其左子节点编号为u<<1,其右节点编号为u<<1|1。一个朴素的想法是:我们在DFS过程中使用两个哈希表......
  • 662. 二叉树最大宽度
    662.二叉树最大宽度给你一棵二叉树的根节点root,返回树的最大宽度。树的最大宽度是所有层中最大的宽度。每一层的宽度被定义为该层最左和最右的非空节点......
  • 二叉树
    1树的结构 1.1树的概念:树是一种非线性的数据结构,它是由n(n>=0)个有限结点组成一个具有层次关系的集合。有一个特殊的节点叫根节点,根节点没有前驱。其余节点被分成......
  • 222.count-complete-tree-nodes 完全二叉树的节点个数
    遍历法遍历所有节点的方法,时间复杂度为\(O(n)\)classSolution{public:intcountNodes(TreeNode*root){if(root==nullptr)return0......
  • 101. 对称二叉树
    101.对称二叉树给你一个二叉树的根节点root,检查它是否轴对称。 示例1:输入:root=[1,2,2,3,4,4,3]输出:true示例2:输入:root=[1,2,2,null,3,null,3]输出:fa......
  • leetcode144:二叉树的前序遍历
    packagecom.mxnet;importjava.util.ArrayList;importjava.util.List;publicclassSolution144{publicstaticvoidmain(String[]args){}/**......
  • leetcode226-翻转二叉树
    翻转二叉树递归classSolution{publicTreeNodeinvertTree(TreeNoderoot){if(root==null)returnroot;TreeNodel=invertTree(roo......
  • leetcode222-完全二叉树的节点个数
    完全二叉树的节点个数递归classSolution{publicintcountNodes(TreeNoderoot){if(root==null)return0;returncountNodes(root.le......