您的位置:首页 > 编程语言 > Java开发

java实现二叉树查找,先,中,后序编列

2013-04-05 09:08 337 查看
请看代码!

package com.rihui.eightSort;

/**

*

* @author 吴日辉

*

*/

public class MyBinaryTree {

public int data;

public MyBinaryTree left;

public MyBinaryTree right;

public MyBinaryTree(int data){

this.data=data;

this.left=null;

this.right=null;

}

//insert

public void insert(MyBinaryTree root,int data){

if(data>root.data){

//放到右子树中,判断该节点是否有右孩子

if(root.right==null){

//如果没有,则直接放到右边

root.right=new MyBinaryTree(data);

}else{

//如果有,递归

insert(root.right,data);

}

}else{

//放到左子树中,判断该节点是否有左孩子

if(root.left==null){

//如果没有,则直接放到左边

root.left=new MyBinaryTree(data);

}else{

//如果有,递归

insert(root.left,data);

}

}

}

//计算该树的高度

public int getHeight(MyBinaryTree root){

if(this==null){

return -1;

}

int treeHeight=0;

int leftHeight=root.left==null?0:getHeight(root.left);

int rightHeight=root.right==null?0:getHeight(root.right);

treeHeight=leftHeight>=rightHeight?leftHeight:rightHeight;

return treeHeight+1;

}

//先序遍历

public void firstOrder(MyBinaryTree root){

if(root!=null){

System.out.print(root.data+" ");

firstOrder(root.left);

firstOrder(root.right);

}

}

//中序遍历

public void middleOrder(MyBinaryTree root){

if(root!=null){

middleOrder(root.left);

System.out.print(root.data+" ");

middleOrder(root.right);

}

}

//后序遍历

public void lastOrder(MyBinaryTree root){

if(root!=null){

lastOrder(root.left);

lastOrder(root.right);

System.out.print(root.data+" ");

}

}

//二叉树查找

public boolean find(MyBinaryTree root,int key){

if(root==null){

return false;

}else if(root.data==key){

return true;

}else if(key>root.data){

//递归右边子树

return find(root.right,key);

}else{

//递归左子树

return find(root.left, key);

}

}

//测试

public static void main(String[] args){

int[] arr={3,2,5,4};

MyBinaryTree root=new MyBinaryTree(arr[0]);

//初始化二叉树

for(int i=1;i<arr.length;i++){

root.insert(root, arr[i]);

}

//打印树的高度

System.out.println(root.getHeight(root));

//打印先序遍历

root.firstOrder(root);

System.out.println();

//打印中序遍历

root.middleOrder(root);

System.out.println();

//打印后序遍历

root.lastOrder(root);

//二叉树查找目标元素

System.out.println(root.find(root, 6));

}

}

总结:深刻理解递归思想,以及树这种结构的优势!

建议:不要觉得看懂了就好,一定要动手敲一遍!

分享 :纸上得来终觉浅,绝知此事要躬行!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: