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

二叉树-构造二叉树

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

二叉树-构造二叉树

文章目录
    • 前序+中序构造二叉树
    • 前序+后序构造二叉树
    • 前序遍历构造二叉搜索树

前序+中序构造二叉树

105. 从前序与中序遍历序列构造二叉树

class Solution {
    Listam=new ArrayList<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return dfs(preorder,0,preorder.length-1,inorder,0,inorder.length-1);

    }

    private TreeNode dfs(int[] preorder, int pL, int pR, int[] inorder, int iL, int iR) {
        if(pL>pR) return null;

        TreeNode root=new TreeNode(preorder[pL]);
//        am.add(preorder[pL]);如果是求后序遍历的序列,就在这里记录即可,万变不离其宗

        //在中序遍历中找到根节点的位置
        int idx=0;
        while (inorder[idx]!=preorder[pL]){
            idx++;
        }
        int pLen=idx-iL;

        root.left=dfs(preorder,pL+1,pL+pLen,inorder,iL,idx-1);
        root.right=dfs(preorder,pL+pLen+1,pR,inorder,idx+1,iR);
        return root;
    }

}
前序+后序构造二叉树

添加链接描述
没有中序也是可以构造的

举例:
前序遍历为 [1] + [2, 4, 5] + [3, 6, 7],
后序遍历为 [4, 5, 2] + [6, 7, 3] + [1].

找左分支的头节点,上栗中就是2,在前序中的下标preLeft+1,如果令左分支有 L 个节点的话。在后序中的下标则为L-1。

class Solution {
    public TreeNode constructFromPrePost(int[] pre, int[] post) {
        return build(pre,post,0,pre.length-1,0,post.length-1);
    }

    private TreeNode build(int[] pre, int[] post, int pl, int pr, int ql, int qr) {
        if(pl>pr){
            return null;
        }
        TreeNode node=new TreeNode(pre[pl]);
        if(pl==pr){ //不能掉
            return node;
        }
        //计算leftLen
        int p=ql;
        while (post[p]!=pre[pl+1]) {
            p++;
        }
        int leftLen=p-ql+1;
        node.left=build(pre,post,pl+1,pl+leftLen,ql,ql+leftLen-1);
        node.right=build(pre,post,pl+leftLen+1,pr,ql+leftLen,qr-1);
        return node;
    }
}
前序遍历构造二叉搜索树

添加链接描述
对preorder排序得到中序遍历,前+中=》bst

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

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

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