什么是平衡二叉树(BBT)?
1. |当前节点的左子树高度-当前节点的右子树高度| <= 1
2. 左子树和右子树也是平衡二叉树
代码实现:
public class BalancedTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
static class ReturnType {
public boolean isBalanced;
public int height;
public ReturnType(boolean isBalanced, int height) {
this.isBalanced = isBalanced;
this.height = height;
}
}
public static boolean isBalanced(Node head) {
return process(head).isBalanced;
}
public static ReturnType process(Node x) {
if (x == null) {
return new ReturnType(true, 0);
}
ReturnType leftData = process(x.left);
ReturnType rightData = process(x.right);
int height = Math.max(leftData.height, rightData.height) + 1;
boolean isBalanced = leftData.isBalanced &&
rightData.isBalanced &&
Math.abs(leftData.height - rightData.height) <= 1;
return new ReturnType(isBalanced, height);
}
}