基础算法----二叉排序树的实现

本文介绍了一种使用二叉排序树实现排序的方法。首先构造一棵二叉排序树,然后利用中序遍历的方式输出排序后的结果。该方法简单易懂,适合初学者理解二叉树与排序算法的基本原理。

一、二叉排序树的实现排序算法:

1构造一个二叉排序树:

class SortTree{
	public static void main(String[] args) {
	        int a[] = new int[]{4,5,1,7,3,9,6,2};
	        Node[] nodes = new Node[a.length];
	        Node root = new Node(a[0]);
	        for (int i = 1; i < a.length; i++) {
	            nodes[i] = new Node(a[i]);
	            insert(root,nodes[i]);
	        }
	        print_mid(root);
	
	    }
	public static void insert(Node root,Node insert_node){
	        if(root == null){
	            root = insert_node;
	        }
	
	        if(insert_node.val<root.val){
	           //插入左子树
	           if(root.left == null){
	               root.left = insert_node;
	           }else{
	               insert(root.left,insert_node);
	           }
	        }else{
	            //插入右子树
	            if(root.right == null){
	                root.right = insert_node;
	            }else{
	                insert(root.right,insert_node);
	            }
	        }
	    }

}

class Node{
    public int val;
    public Node left;
    public Node right;

    public Node(int val){
        this.val = val;
    }
}

通过插入进行构造树之后,使用中序遍历进行排序:

public static void print_mid(Node root){
        if(root !=null){
            print_mid(root.left);
            System.out.println(root.val);
            print_mid(root.right);
        }
        return;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值