1.平衡二叉树
1.1左边所有的子树必须满足平衡二叉树条件
1.2右边所有的子树必须满足平衡二叉树条件
1.3 左子树 和 右子树 的高度差 小于 2
2.代码实现
2.1准备节点
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
2.2 实现判断代码
/**
* balance binary tree
* nonuse container
* 1.left tree isBalanced tree
* 2.right tree isBalanced tree
* 3.| left height - right height | > 1
* @param head
* @return
*/
public static boolean isBalanced(Node head) {
if(head == null) {
return true;
}
return process(head).isBalanced;
}
public static class Info{
private boolean isBalanced;
private int height;
public Info(boolean isBalanced, int height) {
this.isBalanced = isBalanced;
this.height = height;
}
}
/**
* core code
* @param node
* @return
*/
public static Info process(Node node) {
if(node == null){
return new Info(true,0);
}
Info left = process(node.left);
Info right = process(node.right);
int height = Math.max(left.height,right.height) + 1;
boolean isBalanced = true;
if(!left.isBalanced || !right.isBalanced){
isBalanced = false;
}
if(Math.abs(left.height - right.height) > 1){
isBalanced = false;
}
return new Info(isBalanced,height);
}