不bb基础了,直接开干
使用递归本身就是借助了栈的思想。
*前中后和层序遍历四种遍历算法的实现
public class BinarySearchTree {
BinarySearchTree[] queue = new BinarySearchTree[200];
int front=0,rear=0;
int data;
BinarySearchTree left;
BinarySearchTree right;
/**
* 二叉树的构造方法,构造方法不能有返回值,void也不行
* @param data
*/
public BinarySearchTree(int data){
this.data = data;
left = null;
right = null;
}
/**
* 二叉树的插入方法
* @param root
* @param data
*/
public static void insert(BinarySearchTree root, int data){
if (root.data < data){
if (root.right == null){
root.right = new BinarySearchTree(data);
}else {
insert(root.right,data);
}
}else {
if (root.left == null){
root.left = new BinarySearchTree(data);
}else {
insert(root.left,data);
}
}
}
public void delect(BinarySearchTree root , int data){
}
/**
* 中序遍历 左根右
* @param root
*/
public static void inorder(BinarySearchTree root){
if (root != null){
inorder(root.left);
System.out.print(root.data+" ");
inorder(root.right);
}
}
/**
* 前序遍历 根左右
* @param root
*/
public static void preorder(BinarySearchTree root){
if (root != null){
System.out.print(root.data+" ");
preorder(root.left);
preorder(root.right);
}
}
/**
* 后序遍历 左右根
* @param root
*/
public static void postorder(BinarySearchTree root){
if (root != null){
postorder(root.left);
postorder(root.right);
System.out.print(root.data+" ");
}
}
public void levelroder(){
BinarySearchTree root;
while(front < rear){
root = OutQueue();
if (root.left != null){
EnQueue(root.left);
}
if (root.right != null){
EnQueue(root.right);
}
}
}
/**
* 进队
* @param root
*/
public void EnQueue(BinarySearchTree root){
queue[rear++] = root;
}
/**
* 出队
* @param
*/
public BinarySearchTree OutQueue(){
System.out.print(queue[front].data+ " ");
return queue[front++];
}
public static void main(String[] args) {
int data[] = {6,1,2,5,4,62,52,7,9,0};
BinarySearchTree root = new BinarySearchTree(data[0]);
root.EnQueue(root);
for (int i = 1 ; i< data.length; i++){
root.insert(root,data[i]);
}
System.out.println("中序遍历:");
inorder(root); //对方法的直接调用,不用示例对象调用,方法需要设置为静态方法
System.out.println("\n"+"前序遍历:");
preorder(root); //前序
System.out.println("\n"+"后序遍历:");
postorder(root); //后序
System.out.println("\n"+"层序遍历:");
root.levelroder();
}
}