class Tree{
int v;
Tree left;
Tree right;
}
public class TreeDepth {
public static void main(String[] args) {
int data[]={10,5,12,4,7};
Tree t=creat(data, 0);
System.out.println(getdepth(t));
System.out.println(isBananceTree(t));
}
//从数组中递归创建树,i 数组中的第i个元素,返回树的根节点
public static Tree creat(int [] data,int i){
if(data==null || i<0||i>=data.length){
return null;
}else{
Tree root = new Tree();
root.v=data[i];
root.left=creat(data, (i<<1)+1);
root.right=creat(data, (i<<1)+2);
return root;
}
}
//得到树的深度
public static int getdepth(Tree t){
if(t==null){
return 0;
}else{
int i1=getdepth(t.left);
int i2=getdepth(t.right);
return Math.max(i1, i2)+1;
}
}
//用后序遍历的方法判断二叉树是否是平衡树
public static boolean isBananceTree(Tree t){
if(t==null){
return true;
}else{
if(isBananceTree(t.left)&&isBananceTree(t.right)){
int leftdepth=getdepth(t.left);
int rightdepth=getdepth(t.right);
if(Math.abs(leftdepth-rightdepth)<=1){
return true;
}else{
return false;
}
}else{
return false;
}
}
}
}