二叉排序树,即二叉查找树,它具有如下的特点:
- 如果左子树不为空,那么左子树上的所有结点均小于它的根节点的值。
- 如果右子树不为空,那么右子树上的所有结点均大于它的根节点的值。
- 左右子树也分别为二叉排序树。
二叉排序树的代码如下所示:
package BiTree;
/*
* 实现一棵二叉排序树
* 2
* 1 8
* 7 9
* 4 7
* 3 6
* 5
*
*/
class Node{
public int data;
public Node right;
public Node left;
public Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
public class BinaryTree {
private Node root;
public BinaryTree(){
root=null;
}
//将data数据插入到二叉树中
public void insert(int data){
Node newNode=new Node(data);
if(root==null){
root=newNode;
}else{
Node current=root;
Node parent;
while(true){
parent=current;//当前指针在父节点
if(data<current.data){
current=current.left;//当前指针在左结点上
if(current==null){
parent.left=newNode;
return;
}
}else{
current=current.right;
if(current==null){
parent.right=newNode;
return;
}
}
}
}
}
/*
* 插入数据
*/
public void buildTree(int[] data){
for (int i=0;i<data.length;i++){
insert(data[i]);
}
}
/*
* 先序遍历排序树
*/
public void preOrder(Node locaRoot){
if(locaRoot!=null){
System.out.print(locaRoot.data+" ");
preOrder(locaRoot.left);
preOrder(locaRoot.right);
}
}
public void preOrder(){
this.preOrder(this.root);
}
/*
* 中序遍历
*/
public void midOrder(Node locaRoot){
if(locaRoot!=null){
midOrder(locaRoot.left);
System.out.print(locaRoot.data+" ");
midOrder(locaRoot.right);
}
}
public void midOrder(){
this.midOrder(this.root);
}
/*
* 后序遍历
*/
public void postOrder(Node locaRoot){
if(locaRoot!=null){
postOrder(locaRoot.left);
postOrder(locaRoot.right);
System.out.print(locaRoot.data+" ");
}
}
public void postOrder(){
this.postOrder(this.root);
}
public static void main(String[] args){
BinaryTree btree=new BinaryTree();
int []num={2,8,7,4,9,3,1,6,7,5};
btree.buildTree(num);
System.out.println("先序遍历");
btree.preOrder();
System.out.println();
System.out.println("中序遍历");
btree.midOrder();
System.out.println();
System.out.println("后序遍历");
btree.postOrder();
System.out.println();
/*
* print:
*
* 先序遍历
2 1 8 7 4 3 6 5 7 9
中序遍历
1 2 3 4 5 6 7 7 8 9
后序遍历
1 3 5 6 4 7 7 9 8 2
*/
}
}