平衡二叉树的定义是:
它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
我们要判断是否为平衡二叉树就要一直递归判断它的子树是否为平衡二叉树,一层层去判断。
代码如下所示:
package problems_2017_08_21;
/**
* @author islongfei
* 判断二叉树是否为平衡二叉树
* (它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。)
【题目】
平衡二叉树的性质为:要么是一棵空树,要么任何一个节点的左右子树高度差的绝对值不超过1。
给定一棵二叉树的头节点head,判断这棵二叉树是否为平衡二叉树。
*/
public class Problem_02_IsBalancedTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static boolean isBalance(Node head) {
boolean[] res = new boolean[1];
res[0] = true;
getHeight(head, 1, res);
return res[0];
}
/**
* @param head 头节点
* @param level 树的高度
* @param res 表示是否平衡
* @return
*/
public static int getHeight(Node head, int level, boolean[] res) {
if (head == null) {
return level;
}
int lH = getHeight(head.left, level + 1, res);//得到左子树高度
if (!res[0]) {
return level;
}
int rH = getHeight(head.right, level + 1, res);//得到右子树高度
if (!res[0]) {
return level;
}
if (Math.abs(lH - rH) > 1) {
res[0] = false;
}
return Math.max(lH, rH);
}
public static void main(String[] args) {
Node head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.left.right = new Node(5);
head.right.left = new Node(6);
head.right.right = new Node(7);
System.out.println(isBalance(head));
}
}