题目
平衡的定义如下,已知对于树中的任意一个结点,若其两颗子树的高度差不超过1,则我们称该树平衡。现给定指向树根结点的指针TreeNode* root,请编写函数返回一个bool,表示该二叉树是否平衡。
分析
平衡二叉树是通过左右子树的高度来判断是否为平衡二叉树的,所以我们首先想到的是如何求一个树的高度,求一个树的高度可以用递归求解,每次求出左右子树的最大高度再加1便是父节点的高度,这样递归下去,便可以求出任何一颗树的高度。
可以求出任何一个节点的高度,那么通过再次遍历二叉树,判断任何一个节点的左右子树高度相差是否满足平衡二叉树便可实现平衡二叉树的判断。
代码
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Balance {
public boolean isBalance(TreeNode root) {
// write code here
if (root == null) {
return true;
}
int deepLeft = nodeDeep(root.left);
int deepRight = nodeDeep(root.right);
if (Math.abs(deepLeft-deepRight) > 1)
return false;
return isBalance(root.left)&&isBalance(root.right);
}
private int nodeDeep(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left==null && root.right==null)
return 1;
int deepLeft = 0;
int deepRight = 0;
if (root.left != null) {
deepLeft = nodeDeep(root.left);
}
if (root.right != null) {
deepRight = nodeDeep(root.right);
}
return Math.max(deepLeft, deepRight) + 1;
}
}