码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的前、中、后序排列

时间:2021-07-01 17:04:50      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:tree   esc   author   二叉树   const   print   des   highlight   排序   

import lombok.*;

/**
 * @author: Small sunshine
 * @Description:
 * @date: 2021/6/30 8:05 下午
 */
public class SortTree {

    public static void main(String[] args) {
        Tree treeG = new Tree(‘G‘, null, null);
        Tree treeD = new Tree(‘D‘, null, null);
        Tree treeF = new Tree(‘F‘, null, null);
        Tree treeE = new Tree(‘E‘, treeF, null);
        Tree treeB = new Tree(‘B‘, treeD, treeE);
        Tree treeC = new Tree(‘C‘, treeG, null);
        Tree treeA = new Tree(‘A‘, treeB, treeC);
        //前序排列
        System.out.print("前序排列:");
        VLR(treeA);
        System.out.println();
        //中序排列
        System.out.print("中序排列:");
        LDR(treeA);
        System.out.println();
        //后序排列
        System.out.print("后序排列:");
        LRD(treeA);
        System.out.println();


    }

    /**
     * 输出节点
     *
     * @param tree
     */
    public static void print(Tree tree) {
        System.out.print(tree.getData());
    }

    /**
     * 前序排列-VLR
     *
     * @param tree
     */
    public static void VLR(Tree tree) {
        print(tree);
        if (tree.left != null) {
            VLR(tree.left);
        }
        if (tree.right != null) {
            VLR(tree.right);
        }
    }

    /**
     * 中序排序-LDR
     *
     * @param tree
     */
    public static void LDR(Tree tree) {
        if (tree.left != null) {
            LDR(tree.left);
        }
        print(tree);
        if (tree.right != null) {
            LDR(tree.right);
        }
    }

    /**
     * 后序排列-LRD
     *
     * @param tree
     */
    public static void LRD(Tree tree) {
        if (tree.left != null) {
            LRD(tree.left);
        }
        if (tree.right != null) {
            LRD(tree.right);
        }
        print(tree);
    }


    @Data
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Tree {
        private char data;
        private Tree left;
        private Tree right;
    }
}

 

二叉树的前、中、后序排列

标签:tree   esc   author   二叉树   const   print   des   highlight   排序   

原文地址:https://www.cnblogs.com/Small-sunshine/p/14958023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有
迷上了代码!