package tree;
class height{
int h;
}
public class Isbanabalanced {
/**
* 判断一颗二叉树是不是平衡的二叉树,本质是采用后序遍历
* @param args
*/
public static boolean isbalance(TreeNode root){
if(root==null) return true;
height h = new height();
return isbalancecore(root,h);
}
private static boolean isbalancecore(TreeNode root, height h) {
if(root==null) return true;
height left = new height();
height right = new height();
if(isbalancecore(root.left,left)&&isbalancecore(root.right,right)){
int diff = Math.abs(left.h-right.h);
if(diff>=2){
return false;
}
h.h = (left.h>right.h?left.h:right.h)+1;
return true;
}
return false;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
//root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
//root.right.left = new TreeNode(2);
System.out.println(isbalance(root));
}
}
判断一颗二叉树是否平衡
最新推荐文章于 2022-04-25 00:16:22 发布