涉及的知识点
递归
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
输入:
{1,2,3,4,5,6,7}
输出:
true
解题思路
借助于上一题的计算树的深度,然后算左右子树的差值。
代码
import java.lang.Math;
public class Solution {
public int Depth(TreeNode root){
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 1;
}
return Math.max(Depth(root.left),Depth(root.right))+1;
}
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){
return true;
}
if(Math.abs(Depth(root.left)-Depth(root.right))>1){
return false;
}
return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
}
}