题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
思路:
难点:既想返回子树是不是平衡的结果,又想返回子树的深度,但一个方法不能返回两个参数。
解决思路:
1.只要有一个子树不平衡,即树不平衡。用一个全局变量标记是不是平衡,初始设为true,当有子树不平衡,即修改为false。用方法递归求每个节点的深度,判断是否平衡。好处是每个节点只用访问一遍就可以了,求一次树的深度就能知道是否平衡。
2.写一个方法求子树深度,比较左右子树是否平衡,判断一个子树是否平衡看三个条件:左子树是否平衡;右子树是否平衡;左右子树的高度差绝对值是否小于2。
思路一示例:
public class Solution {
boolean balance = true;//用来标记存在不平衡的情况。
public boolean IsBalanced_Solution(TreeNode root) {
depth(root);
return balance;
}
public int depth(TreeNode root){
if(root == null){
return 0;
}
int a = depth(root.left);
int b = depth(root.right);
if(Math.abs(a-b)>1){
balance = false;
}
return Math.max(a,b)+1;
}
}
思路二示例一:
示例一存在重复求子树的高度,有优化空间。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true;
}
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right) &&
Math.abs(depth(root.left)-depth(root.right)) < 2;
}
public int depth(TreeNode root){
if(root == null){
return 0;
}
return Math.max(depth(root.left),depth(root.right))+1;
}
}
示例一重复求子树的高度,改造求树高度的方法,要求当已经判断出子树不是平衡二叉树时,就不要再去求其他子树的高度了,直接向上返回表示非平衡二叉树的数字。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(TreeDepth(root) != -1){
return true;
}
return false;
}
public int TreeDepth(TreeNode root){
if(root == null){
return 0;
}
int l = TreeDepth(root.left);
if(l == -1){
return -1;
}
int r = TreeDepth(root.right);
if(r == -1){
return -1;
}
if(l - r <= 1 && l - r >= -1){
return Math.max(l,r) + 1;
}else{
return -1;
}
}
}