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

通过中序遍历和前序遍历,后续遍历来构建二叉树

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

通过中序遍历和前序遍历,后续遍历来构建二叉树

通过前序遍历和中序遍历构建二叉树
用中序遍历的根节点和第一个左节点获取做节点长度,右节点下标。
通过前序遍历(第一个节点)和后续遍历(最后一个节点)得到根节点

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    
    private TreeNode buildTree(int[] pre, int preRootNodeStart, int preEnd, int inLeftNodeStart, Map inPos) {
        if (preRootNodeStart > preEnd) return null;
        TreeNode root = new TreeNode(pre[preRootNodeStart]);
        // 获取根节点在中序遍历的下标
        int rootIdx = inPos.get(pre[preRootNodeStart]);
        // 获取左子树的长度
        int leftLen = rootIdx - inLeftNodeStart;
        root.left = buildTree(pre, preRootNodeStart + 1, preRootNodeStart + leftLen, inLeftNodeStart, inPos);
        root.right = buildTree(pre, preRootNodeStart + leftLen + 1, preEnd, rootIdx + 1, inPos);
        return root;
    }

    public TreeNode buildTree(int[] pre, int[] in) {
        Map inPos = new HashMap<>();
        for (int i = 0; i < in.length; i++) {
            inPos.put(in[i], i);
        }
        return buildTree(pre, 0, pre.length - 1, 0, inPos);
    }
	    private TreeNode buildTreePrePostArray(int[] post, int postStart, int postEnd, int inStart, Map inPos) {
        if (postStart > postEnd) return null;
        TreeNode root = new TreeNode(post[postEnd]);
        int rootIdx = inPos.get(post[postEnd]);
        int leftLen = rootIdx - inStart;
        root.left = buildTreePrePostArray(post, postStart, postStart + leftLen - 1, inStart, inPos);
        root.right = buildTreePrePostArray(post, postStart +leftLen, postEnd - 1, rootIdx + 1, inPos);
        return root;
    }

    // Time: O(n). Space:O(n)
    public TreeNode buildTreePrePostArray(int[] in, int[] post) {
        Map inPos = new HashMap<>();
        for (int i = 0; i < in.length; i++) {
            inPos.put(in[i], i);
        }
        return buildTreePrePostArray(post, 0, post.length - 1, 0, inPos);
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1014855.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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