什么是平衡二叉树
平衡二叉树,左子树和右子树的高度差不超过1,就认为是平衡二叉树。
解题思路
有两种递归解法,
第一种只需要拿到左树的高度和右树的高度,判断两树差是否大于1 就可以了
第二种是,是把问题拆分成小问题去判断,先判断左树是不是平衡的,并得出高度,再拿到右树是不是平衡的并拿到高度,组合成一颗树时,左右树高度 相差不超过1,就是平衡树。
虽然第二种稍微麻烦一点,但这种思维方式是可以帮助解决复杂问题的,把问题拆成小问题,后面会出几道比较难的题,用这种思路去解决。
递归解法一
定义一个二叉树结构
public class Node {
public int val;
public Node left;
public Node right;
public Node(int data) {
this.val = data;
}
}
第一种解题方案:
public static boolean isBalanced1(Node head){
if (head == null){
return true;
}
boolean[]booleans = new boolean[1];
booleans[0] = true;
process1(head,booleans);
return booleans[0];
}
public static int process1(Node head,boolean[]booleans){
if (!booleans[0] || head == null){
return -1;
}
int left = process1(head.left,booleans);
int right = process1(head.right,booleans);
if (Math.abs(left - right) > 1){
booleans[0] = false;
}
return Math.max(left,right)+1;
}
递归解法二
public static class Info{
int height;
boolean isBalanced;
public Info(int height, boolean isBalanced) {
this.height = height;
this.isBalanced = isBalanced;
}
}
/**
* 递归
* @param head
* @return
*/
public static Info process(Node head){
if (head == null){
return new Info(0,true);
}
Info leftInfo = process(head.left);
Info rightInfo = process(head.right);
int height = Math.max(leftInfo.height,rightInfo.height) + 1;
boolean isBalanced = false;
if (leftInfo.isBalanced && rightInfo.isBalanced){
isBalanced = Math.abs(leftInfo.height-rightInfo.height) < 2 ? true : false;
}
return new Info(height,isBalanced);
}
/**
* 递归
* @param head
* @return
*/
public static boolean isBalanced(Node head){
if (head == null){
return true;
}
Info process = process(head);
return process.isBalanced;
}