java实现二叉排序树实现前中后遍历

本文介绍了一种基于Java的二叉树排序算法实现方法,通过读取输入数据构建二叉树,并演示了先序、中序及后序遍历过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.Scanner;
 
public class BinSort {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int nums = sc.nextInt();
            int values[] = new int[nums];
            for (int i = 0; i < nums; i++) {
                values[i] = sc.nextInt();
            }
            TowTree root = new TowTree(values[0]);
            for (int i = 1; i < values.length; i++) {
                root.addBean(new TowTree(values[i]));
            }
            root.firstRoot();
            System.out.println();
            root.centerRoot();
            System.out.println();
            root.lastRoot();
            System.out.println();
        }
    }
 
    static class TowTree {
        private TowTree left, right;
        private int value;
 
        public TowTree(int value) {
            this.value = value;
        }
 
        public void addBean(TowTree temp) {
            if (temp.value == value)
                return;
            if (temp.value <= value) {
                if (left != null) {
                    left.addBean(temp);
                } else {
                    left = temp;
                }
            } else {
                if (right != null) {
                    right.addBean(temp);
                } else {
                    right = temp;
                }
            }
        }
 
        public void firstRoot() {
            System.out.print(value + " ");
            if (left != null) {
                left.firstRoot();
            }
            if (right != null) {
                right.firstRoot();
            }
        }
 
        public void centerRoot() {
            if (left != null) {
                left.centerRoot();
            }
            System.out.print(value + " ");
            if (right != null) {
                right.centerRoot();
            }
        }
 
        public void lastRoot() {
            if (left != null) {
                left.lastRoot();
            }
            if (right != null) {
                right.lastRoot();
            }
            System.out.print(value + " ");
        }
    }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值