二叉排序树的创建和遍历

二叉排序树的创建和遍历

将一个二叉树中序遍历,就是将这个树的数据升序排列了

package com.wmq.binarysorttree;

/**
 * 二叉排序树
 */
public class BinarySortTreeDemo {
    public static void main(String[] args) {
        int[] arr = {7,3,10,12,5,1,9};
        BinarySortTree binarySortTree = new BinarySortTree();
        //循环加入节点到二叉排序树
        for (int i = 0; i < arr.length; i++) {
            binarySortTree.add(new Node(arr[i]));
        }
        //中序遍历
        System.out.println("中序遍历结果");
        binarySortTree.infixOrder();//1,3,5,7,9,10,12
    }
}
//创建二叉树排序树
class BinarySortTree{
    private Node root;
    public void add(Node node){
        if (root == null){
            root = node;
        }else{
            root.add(node);
        }
    }
    public void infixOrder(){
        if (root != null){
            root.infixOrder();
        }else{
            System.out.println("Error,null");
        }
    }
}
//创建节点
class Node{
    int value;
    Node left;
    Node right;
    public Node(int value){
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    public void add(Node node){
        if (node == null){
            return;
        }
        //判断传入的值和当前节点的大小关系
        if (node.value < this.value){
            if (this.left == null){
                this.left = node;
            }else{
                this.left.add(node);     //递归向左添加节点
            }
        }else{
            if (this.right == null){
                this.right = node;
            }else {
                this.right.add(node);     //递归向右添加节点
            }
        }
    }
    //中序遍历
    public void infixOrder(){
        if (this.left != null){
            this.left.infixOrder();
        }
        System.out.println(this);
        if (this.right != null){
            this.right.infixOrder();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值