平衡二叉树
平衡二叉树的定义:
如果每一个节点的左子树和右子树的高度差不超过1,那么这可树就是平衡二叉树。
判断一个树是否为平衡树,把握三点。
(1)左子树是否平衡 (2)右子树是否平衡 (3)左子树的高度和右子树的高度差值低于1
递归的套路
package class_04;
public class Code_06_IsBalancedTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static class ReturnData{
public boolean isB; // 是否平衡
public int h; // 该节点的高度
public ReturnData(boolean isB, int h) {
this.isB = isB;
this.h = h;
}
}
/*
* 思路:判断一个树是否为平衡树,(1)左子树是否平衡 (2)右子树是否平衡 (3)左子树的高度和右子树的高度差值低于1
* */
public static ReturnData process(Node node) {
if(node == null) { // 判断是否为空,空树是平衡的
return new ReturnData(true, 0);
}
ReturnData leftData= process(node.left); // 判断左子树是否平衡
if(!leftData.isB) {
return new ReturnData(false, 0);
}
ReturnData rightData= process(node.left); // 判断右子树是否平衡
if(!rightData.isB) {
return new ReturnData(false, 0);
}
if(Math.abs(leftData.h - rightData.h) > 1) { // 如果左子树和右子树的高度值差超过1
return new ReturnData(false, 0);
}
return new ReturnData(true, Math.max(leftData.h, rightData.h) + 1); // 往下走高度+1
}
public static boolean isBalance(Node head) {
boolean[] res = new boolean[1];
res[0] = true;
getHeight(head, 1, res);
return res[0];
}
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));
}
}