Java 二叉查找(排序)树 创建 以及中序和层序遍历

来源:互联网 发布:淘宝双11营业额 编辑:程序博客网 时间:2024/06/06 01:43

首先我们需要知道二叉排序树是个什么东西。它或者是一棵空树或者是具有下列性质的二叉树: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);}}

0 0
原创粉丝点击