首先我们需要知道二叉排序树是个什么东西。它或者是一棵空树或者是具有下列性质的二叉树:1.如果左子树不空,那么左子树上所有节点的值均小于它的根节点的值2.如果右子树不空,那么右子树上所有节点的值均小于它的根节点的值3.左右子树也分别为二叉排序树
- import java.util.LinkedList;
- import java.util.Queue;
- class biNode{
- private int data;
- private biNode left;
- private biNode right;
- //构造函数
- public biNode(int data){
- this.data=data;
- this.left=null;
- this.right=null;
- }
- public void setData(int data){
- this.data=data;
- }
- public int getData(){
- return this.data;
- }
- public void setLeft(biNode left){
- this.left=left;
- }
- public biNode getLeft(){
- return this.left;
- }
- public void setRight(biNode right){
- this.right=right;
- }
- public biNode getRight(){
- return this.right;
- }
- }
- public class binarySearchTree {
- private biNode root;
- //构造函数
- public void binarySearchTree(){
- this.root=null;
- }
- //把结点插入二叉树中构造线索二叉树
- public void insert(int data){
- biNode newNode = new biNode(data);
- if(root==null){
- root=newNode;
- }
- else{
- biNode currentNode=root;
- biNode parent;
- //寻找插入位置
- while(true){
- parent=currentNode;
- if(data<currentNode.getData()){
- currentNode=currentNode.getLeft();
- if(currentNode==null){
- parent.setLeft(newNode);
- return;
- }
- }
- else{
- currentNode=currentNode.getRight();
- if(currentNode==null){
- parent.setRight(newNode);
- return;
- }
- }
- }
- }
- }
- //通过一个整数数组构建线索二叉树
- public void buildTree(int[] d){
- for(int i=0;i<d.length;i++){
- insert(d[i]);
- }
- }
- //中序递归遍历线索二叉树
- public void inorder(biNode localRoot){
- if(localRoot!=null){
- inorder(localRoot.getLeft());
- System.out.print(localRoot.getData()+" ");
- inorder(localRoot.getRight());
- }
- }
- //用队列实现层序遍历二叉树
- public void layerTranverse(biNode root){
- //为什么不能创建queue类型的对象 直接
- //Queue<biNode> myq=new Queue<biNode>();
- //因为Queue只是一个接口 Linkedlist才是实现了它的一个具体的类
- Queue<biNode> myq=new LinkedList<biNode>();
- biNode tmp=root;
- if(tmp==null){
- return;
- }
- else{
- myq.add(tmp);
- while(!myq.isEmpty()){
- biNode n=myq.poll();
- System.out.print(n.getData()+" ");
- if(n.getLeft()!=null){
- myq.add(n.getLeft());
- }
- if(n.getRight()!=null){
- myq.add(n.getRight());
- }
- }
- }
- }
- public static void main(String[] args){
- binarySearchTree mytree = new binarySearchTree();
- int[] data={2,8,7,4,9,3,1,6,7,5};
- mytree.buildTree(data);
- mytree.inorder(mytree.root);
- System.out.println();
- mytree.layerTranverse(mytree.root);
- }
- }