栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【LeetCode】Day75-从中序与后序遍历序列构造二叉树

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【LeetCode】Day75-从中序与后序遍历序列构造二叉树

题目

106. 从中序与后序遍历序列构造二叉树【中等】

题解 递归

参照105. 从前序与中序遍历序列构造二叉树的代码

class Solution {
    private MapindexMap;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n=inorder.length;
        indexMap=new HashMap<>();
        for(int i=0;i
            indexMap.put(inorder[i],i);
        }
        return buildTree(inorder,postorder,0,n-1,0,n-1);
    }
    public TreeNode buildTree(int[] inorder, int[] postorder,int inLeft,int inRight,int postLeft,int postRight){
        if(inLeft>inRight)
            return null;
        int postRoot=postRight;//后序的根在数组的位置
        int inRoot=indexMap.get(postorder[postRoot]);//中序的根在数组的位置

        int leftTreeSize=inRoot-inLeft;//左子树结点数目

        TreeNode root=new TreeNode(postorder[postRoot]);
        root.left=buildTree(inorder,postorder,inLeft,inRoot-1,postLeft,postLeft+leftTreeSize-1);
        root.right=buildTree(inorder,postorder,inRoot+1,inRight,postLeft+leftTreeSize,postRoot-1);
        return root;
    }
}

改进
由于在后序遍历序中每次最后一个结点都是子树的根,因此直接用一个指针控制后序遍历的结点位置即可

class Solution {
    private int post_idx;
    private MapindexMap;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n=inorder.length;
        post_idx=n-1;//后序的根
        indexMap=new HashMap<>();
        for(int i=0;i
            indexMap.put(inorder[i],i);
        }
        return buildTree(inorder,postorder,0,n-1);
    }
    public TreeNode buildTree(int[] inorder, int[] postorder,int inLeft,int inRight){
        if(inLeft>inRight)
            return null;
        int inRoot=indexMap.get(postorder[post_idx]);//中序的根在数组的位置

        TreeNode root=new TreeNode(postorder[post_idx]);
        post_idx--;
        //后序是左右根,所以倒着来的话应该先构建右子树再构建左子树
        root.right=buildTree(inorder,postorder,inRoot+1,inRight);
        root.left=buildTree(inorder,postorder,inLeft,inRoot-1);
        return root;
    }
}

时间复杂度: O ( n ) O(n) O(n)

空间复杂度: O ( n ) O(n) O(n)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/939803.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号