题目 判断一棵二叉树是否是平衡二叉树
思路 平衡二叉树,简单来说,二叉树所有的节点,其左子树与右子树的高度差不超过1,这样的二叉树就是平衡二叉树。满树一定是平衡二叉树,而平衡二叉树不一定是满二叉树。
递归求解。设置一个函数递归求解树的高度,高度为左子树与右子树中高度更高的值。递归判断当前子树是否是平衡二叉树,若递归过程出现左右子树高度差大于1的情况,则直接返回false,否则继续递归至当前节点为空,返回true。注意,左子树与右子数都是平衡二叉树,且左子树与右子树的高度差不超过1,整棵树才会是平衡二叉树。
package algorithm.section5;
import java.awt.desktop.AboutEvent;
public class IsBalancedTree {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
public static boolean isBalanceTree(Node head){
if (head == null) return true;
return isBalance(head, 1);
}
public static boolean isBalance(Node head, int level){
if (head == null) return true;
int leftH = getHeight(head.left, level);
int rightH =getHeight(head.right, level);
if (Math.abs(leftH - rightH) > 1) return false;
return isBalance(head.left, level + 1) && isBalance(head.right, level + 1);
}
public static int getHeight(Node head, int level){
if (head == null) return level;
int leftHeight = getHeight(head.left, level + 1);
int rightHeight = getHeight(head.right, level + 1);
return Math.max(leftHeight, rightHeight);
}
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);
head.right.right.right = new Node(8);
System.out.print(isBalanceTree(head));
}
}
方法二:设置一个类保存返回值,包括平衡树的高度,以及是否平衡,若不平衡则其高度为1。
package algorithm.section5;
public class IsBalancedTree2 {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
public static class ReturnData{
public int height;
public boolean isBalance;
public ReturnData(int height, boolean isBalance){
this.height = height;
this.isBalance = isBalance;
}
}
public static ReturnData isBalancedTree(Node head){
if (head == null) return new ReturnData(0, true);
ReturnData left = isBalancedTree(head.left);
if (!left.isBalance) return new ReturnData(0, false);
ReturnData right = isBalancedTree(head.right);
if (!right.isBalance) return new ReturnData(0, false);
if (Math.abs(left.height - right.height) > 1) return new ReturnData(0, false);
return new ReturnData(Math.max(left.height, right.height) + 1, true);
}
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);
head.right.right.right = new Node(8);
System.out.print(isBalancedTree(head).isBalance);
}
}