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

Java实现二叉树前中后层遍历算法-数据结构和算法06

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

Java实现二叉树前中后层遍历算法-数据结构和算法06

  最近在学习数据结构和算法,嗯,在看大话数据结构,边看边学习边总结一些东西把。记录下关键的节点
  实现二叉树前中后层排序算法,也是看到C的算法实现了,想着自己搞下java的把。

口诀

DLR–前序遍历(根在前,从左往右,一棵树的根永远在左子树前面,左子树又永远在右子树前面 )
LDR–中序遍历(根在中,从左往右,一棵树的左子树永远在根前面,根永远在右子树前面)
LRD–后序遍历(根在后,从左往右,一棵树的左子树永远在右子树前面,右子树永远在根前面)

书上的前序遍历

看下书上实现的遍历算法:

是不是很简单。。嘿嘿。。后边的就不贴出来了。

造一棵树

先看结果:

1 2 4 8 9 5 3 6 7 前序遍历
8 4 9 2 5 1 6 3 7 中序遍历
8 9 4 5 2 6 7 3 1 后序遍历
1 2 3 4 5 6 7 8 9 层序遍历
Java实现前中后层遍历算法
package com.my.data.structure;

import java.util.LinkedList;


public class TreeSort {

    
    class TreeNode {
        TreeNode leftTree = null;
        TreeNode rightTree = null;
        int curValue;

        TreeNode(int v) {
            this.curValue = v;
        }

        public void printValue() {
            System.out.print(this.curValue + " ");
        }
    }

    
    public TreeNode createTree() {
        TreeNode[] treeNodes = new TreeNode[10];
        for (int i = 1; i < 10; i++) {
            treeNodes[i] = new TreeNode(i);
        }
        for (int i = 1; i < 5; i++) {
            int left = 2 * i;
            int right = 2 * i + 1;
            treeNodes[i].leftTree = treeNodes[left];
            treeNodes[i].rightTree = treeNodes[right];
        }
        return treeNodes[1];
    }

    
    public void preSort(TreeNode root) {
        if (root == null) return;
        root.printValue();
        preSort(root.leftTree);
        preSort(root.rightTree);
    }

    
    public void middleSort(TreeNode root) {
        if (root == null) return;
        middleSort(root.leftTree);
        root.printValue();
        middleSort(root.rightTree);
    }

    
    public void lastSort(TreeNode root) {
        if (root == null) return;
        lastSort(root.leftTree);
        lastSort(root.rightTree);
        root.printValue();
    }

    
    public void levelSort(TreeNode root) {
        if (root == null) return;
        LinkedList queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            root = queue.pollFirst();
            root.printValue();
            if (root.leftTree != null) queue.add(root.leftTree);
            if (root.rightTree != null) queue.add(root.rightTree);
        }

    }

    public static void main(String[] args) {
        TreeSort treeSort = new TreeSort();
        TreeNode root = treeSort.createTree();

        treeSort.preSort(root);
        System.out.println("前序遍历");

        treeSort.middleSort(root);
        System.out.println("中序遍历");

        treeSort.lastSort(root);
        System.out.println("后序遍历");

        treeSort.levelSort(root);
        System.out.println("层序遍历");
    }
}

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

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

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