详解java二叉排序树_java实现二叉排序树

什么是二叉排序树:二叉排序树或者是一颗空树,或者具有以下性质的二叉树:

(1)若它的左子树不为空,则左子树上的所有节点的值都小于他的父节点的值;

(2)若它的右子树不为空,则右子树上的所有节点的值都大于他的父节点的值;

(3)它的左右子树也分别为二叉排序树;

java实例:

package com.test.linked;

public class HeapSort {

public class Node{

private int data;

private Node leftChildren;

private Node rightChildren;

public Node(int data){

this.data=data;

}

public String toString(){

return " "+data;

}

}

public Node root;

/**

* 插入结点

* @param in

*/

public void insert(Node in){

if(root==null){//当为空树时将结点当作根节点

root=in;

}else{

Node current=root;

Node parent;//当作parent

while(current!=null){//当循环到空时结束

parent=current;

if(in.data

current=current.leftChildren;

if(current==null){//当左边子节点为空意味着找到了要插入的位置

parent.leftChildren=in;

}

}else{//否则往右边走

current=current.rightChildren;

if(current==null){

parent.rightChildren=in;

}

}

}

}

}

/**

* 查找元素

* @param key

*/

public void find(int key){

Node current=root;

int deep=1;

if(current!=null){//判断根节点是否为空

while(current.data!=key){

if(key

current=current.leftChildren;

}else{

current=current.rightChildren;

}

deep++;//查找的结点在第几层;

if(current==null){

System.out.println("Node can't be found");

return;

}

}

System.out.println("this Node is :"+current+"at deep:"+deep);

}else{

System.out.println("this tree is null");

}

}

/**

* 遍历二叉树(在这里是先序遍历)利用递归自己遍历自己,直到所有节点都被遍历

* @param node

*/

public void display(Node node){

if(node!=null){

System.out.println(node.data);

display(node.leftChildren);

display(node.rightChildren);

}

}

public static void main(String[] args){

HeapSort sort=new HeapSort();

Node n1=sort.new Node(60);

Node n2=sort.new Node(50);

Node n3=sort.new Node(80);

Node n4=sort.new Node(20);

Node n5=sort.new Node(55);

Node n6=sort.new Node(62);

Node n7=sort.new Node(90);

sort.insert(n1);

sort.insert(n2);

sort.insert(n3);

sort.insert(n4);

sort.insert(n5);

sort.insert(n6);

sort.insert(n7);

sort.find(55);

sort.display(n1);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值