判断一棵二叉树是否是平衡二叉树
程序员文章站
2022-05-16 14:56:16
...
判断一棵二叉树是否是平衡二叉树
public class IsBalancedTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
public static boolean isBalance(Node head) {
boolean[] b = new boolean[1];
b[0] = true;
getHeight(head, 1, b);
return b[0];
}
public static int getHeight(Node head, int level, boolean[] b) {
if (head == null) {
return level;
}
int lH = getHeight(head.left, level + 1, b);
if (!b[0]) {
return level;
}
int rH = getHeight(head.right, level + 1, b);
if (!b[0]) {
return level;
}
if (Math.abs(lH - rH) > 1) {
b[0] = false;
}
return Math.max(lH, rH);
}
上一篇: 力扣:101. 对称二叉树
下一篇: 判断一棵树是否是平衡二叉树