/**
* Created by Administrator on 2015/10/10.
*/
public class TreeNode {
//树节点的值
private char data;
//节点的左子树
private TreeNode leftTree;
//节点的右子树
private TreeNode rightTree;
public TreeNode(char data,TreeNode leftTree,TreeNode rightTree){
this.data=data;
this.leftTree=leftTree;
this.rightTree=rightTree;
}
public int getData() {
return data;
}
public void setData(char data) {
this.data = data;
}
public TreeNode getLeftTree() {
return leftTree;
}
public void setLeftTree(TreeNode leftTree) {
this.leftTree = leftTree;
}
public TreeNode getRightTree() {
return rightTree;
}
public void setRightTree(TreeNode rightTree) {
this.rightTree = rightTree;
}
public static int getDepth(TreeNode pNode){
if(pNode==null){
return -1;
}
TreeNode leftTree=pNode.getLeftTree();
TreeNode rightTree=pNode.getRightTree();
if(leftTree==null||rightTree==null){
return 0;
}
int leftDepth=getDepth(leftTree);
int rightDepth=getDepth(rightTree);
int depth=leftDepth>rightDepth?leftDepth:rightDepth;
return depth+1;
}
//判断二叉树是否为一个平衡二叉树
public static boolean isBalance(TreeNode pNode){
if (pNode==null){
return true;
}
TreeNode leftTree=pNode.getLeftTree();
TreeNode rightTree=pNode.getRightTree();
int leftDepth=getDepth(leftTree);
int rightDepth=getDepth(rightTree);
if(leftDepth-rightDepth>1||rightDepth-leftDepth>1){
return false;
}
if(isBalance(leftTree)){
return isBalance(rightTree);
}else{
return false;
}
}
//测试
public static void main(String[] args){
//TreeNode D=new TreeNode('D',null,null);
TreeNode E=new TreeNode('E',null,null);
TreeNode F=new TreeNode('F',null,null);
TreeNode C=new TreeNode('C',E,F);
//TreeNode B=new TreeNode('B',D,null);
TreeNode A=new TreeNode('A',null,C);
System.out.println(isBalance(A));
//System.out.println(getDepth(A));
}
}