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

请看代码!

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));
}
}

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

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

分享 :纸上得来终觉浅,绝知此事要躬行!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值