请看代码!
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));
}
}
总结:深刻理解递归思想,以及树这种结构的优势!
建议:不要觉得看懂了就好,一定要动手敲一遍!
分享 :纸上得来终觉浅,绝知此事要躬行!