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

二叉树的遍历(java)

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

二叉树的遍历(java)

二叉树作为一种数据结构,其遍历方式也是重要的一个内容

对于二叉树的遍历,我用的是队列去进行存放树中的数据,基于队列的先进先出的思想,能够很好的实现二叉树的遍历

一、前序遍历

前序遍历是先从根节点开始向左节点遍历,直到最左节点也走到后就开始从最左节点的右节点开始遍历

 

 前序遍历结果:EBADCGFH

 private void preErgodic(Node x,Queue keys){
        if (x == null){
            return;
        }
        keys.enqueue(x.key);
        if (x.left != null){
            preErgodic(x.left,keys);
        }
        if (x.right != null){
            preErgodic(x.right,keys);
        }
    }
二、中序遍历

中序遍历是先遍历左子树,然后访问根节点,最后遍历右子树。可以看作是从左到右,上面的节点垂直下来一排

                          

  中序遍历结果:ABCDEFGH

private void midErgodic(Node x,Queue keys){
        if (x == null){
            return;
        }
        if (x.left != null){
            midErgodic(x.left,keys);
        }
        keys.enqueue(x.key);
        if (x.right != null){
            midErgodic(x.right,keys);
        }
    }
三、后序遍历

后序遍历是先左后右再根,先把左子树从下往上遍历完再把右子树从下往上遍历,然后访问根节点

                         

 

后序遍历结果:ACDBFHGE

private void afterErgodic(Node x,Queue keys){
        if (x == null){
            return;
        }
        if (x.left != null){
            afterErgodic(x.left,keys);
        }
        if (x.right != null){
            afterErgodic(x.right,keys);
        }
        keys.enqueue(x.key);
    }
四、层序遍历

层序遍历就比较简单好理解了,从根节点开始从上往下从左往右每一层遍历

                         

 层序遍历结果:EBGADFHC

 public Queue layerErgodic(){
        Queue keys = new Queue<>();
        Queue nodes = new Queue<>();
        nodes.enqueue(root);
        while (!nodes.isEmpty()){
            Node n = nodes.dequeue();
            keys.enqueue(n.key);
            if (n.left != null){
                nodes.enqueue(n.left);
            }
            if (n.right != null){
                nodes.enqueue(n.right);
            }
        }
        return keys;
    }

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

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

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