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

如何根据“前序遍历,中序遍历”,“中序遍历,后序遍历”构建按二叉树

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

如何根据“前序遍历,中序遍历”,“中序遍历,后序遍历”构建按二叉树

如何根据前序遍历和中序遍历,或者中序遍历和后序遍历创建二叉树?大致思路如下文章;

http://t.csdn.cn/wBUiy


 分析:

 

 

代码如下: 

class Solution {
    public int preIndex;
    public TreeNode buildTreeChild(int[] preorder, int[] inorder, int inBegan, int inEnd){
        //如果ib > ie说明递归终止
        if(inBegan > inEnd){
            return null;
        }
        //创建根节点
        TreeNode root = new TreeNode(preorder[preIndex]);
        //在中序遍历中找到对应的根节点下标
        int InorderIndex = fundInorderIndex(inorder, preorder[preIndex], inBegan, inEnd);
        //前序遍历中的下标继续往后遍历
        preIndex++;
        //通过递归继续创建左子树和右子树
        root.left = buildTreeChild(preorder, inorder, inBegan, InorderIndex - 1);
        root.right = buildTreeChild(preorder, inorder, InorderIndex + 1, inEnd);
        //最后返回根结点即可
        return root;
    }
    public int fundInorderIndex(int[] inorder, int val, int inBegan, int inEnd){
        for(int i = inBegan; i <= inEnd; i++){
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder, inorder, 0, inorder.length - 1);
    }
}

分析: 

         和前序与中序遍历的思路一样,但是注意的是,后序遍历中是从后向前找根结点,因此,当你写出后序遍历的顺序的时候,会发现需要先创建右子树,再创建左子树。

代码如下:

class Solution {
    public int preIndex;
    public TreeNode buildTreeChild(int[] postorder, int[] inorder, int inBegan, int inEnd){
        //如果ib > ie说明递归终止
        if(inBegan > inEnd){
            return null;
        }
        //创建根节点
        TreeNode root = new TreeNode(postorder[preIndex]);
        //在中序遍历中找到对应的根节点下标
        int InorderIndex = fundInorderIndex(inorder, postorder[preIndex], inBegan, inEnd);
        //前序遍历中的下标继续往后遍历
        preIndex--;
        //这里要注意,先构建左树再构建右树!
        root.right = buildTreeChild(postorder, inorder, InorderIndex + 1, inEnd);
        root.left = buildTreeChild(postorder, inorder, inBegan, InorderIndex - 1);

        //最后返回根结点即可
        return root;
    }
    public int fundInorderIndex(int[] inorder, int val, int inBegan, int inEnd){
        for(int i = inBegan; i <= inEnd; i++){
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        preIndex = postorder.length - 1;
        return buildTreeChild(postorder, inorder, 0, inorder.length - 1);
    }
}

 

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

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

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