package test;
public class TreeDepth {
public class BinaryTreeNode{
int m_nValue;
BinaryTreeNode m_pLeft;
BinaryTreeNode m_pRight;
}
public int treeDepth(BinaryTreeNode root){
if(root == null){
return 0;
}
int Left = treeDepth(root.m_pLeft);
int Right = treeDepth(root.m_pRight);
return (Left>Right)? (Left+1) :(Right+1);
}
public boolean IsBalance(BinaryTreeNode root){
if(root == null){
return true;
}
int left = treeDepth(root.m_pLeft);
int right = treeDepth(root.m_pRight);
int diff = left - right;
if(diff>1 || diff<-1){
return false;
}
return IsBalance(root.m_pLeft)&& IsBalance(root.m_pRight);
}
public BinaryTreeNode createTree(){
BinaryTreeNode root = new BinaryTreeNode();
root.m_nValue = 1;
BinaryTreeNode n2 = new BinaryTreeNode();
n2.m_nValue = 2;
BinaryTreeNode n3 = new BinaryTreeNode();
n3.m_nValue = 3;
BinaryTreeNode n4 = new BinaryTreeNode();
n4.m_nValue = 4;
BinaryTreeNode n5 = new BinaryTreeNode();
n5.m_nValue = 5;
BinaryTreeNode n6 = new BinaryTreeNode();
n6.m_nValue = 6;
BinaryTreeNode n7 = new BinaryTreeNode();
n7.m_nValue = 7;
root.m_pLeft = n2;
root.m_pRight = n3;
n2.m_pLeft = n4;
n2.m_pRight = n5;
n5.m_pLeft = n7;
n3.m_pRight= n6;
return root;
}
public boolean IsBalanced(BinaryTreeNode root, int pDepth){
if(root == null){
pDepth = 0;
return true;
}
int left=0 ,right=0;
if(IsBalanced(root.m_pLeft, left)&&IsBalanced(root.m_pRight, right)){
int diff = left - right;
if(diff <=1 && diff >=-1){
pDepth = 1+(left > right? left: right);
System.out.println("pDepth :"+pDepth+"+++++++++==root:"+root.m_nValue);
return true;
}
}
return false;
}
public boolean IsBalanced(BinaryTreeNode root){
int pDepht = 0;
return IsBalanced(root,pDepht);
}
public static void main(String[] args){
TreeDepth treeDepth = new TreeDepth();
BinaryTreeNode root = treeDepth.createTree();
// System.out.println(treeDepth.treeDepth(root));
//
// System.out.println(treeDepth.IsBalance(root));
System.out.println(treeDepth.IsBalanced(root));
}
}
剑指Offer 39题 二叉树的深度 && 判断平衡二叉树 Java版
最新推荐文章于 2020-08-04 23:28:43 发布