前言
仅记录学习笔记,如有错误欢迎指正。
题目
输入一棵节点数为 n 二叉树,判断该二叉树是否是平衡二叉树。 在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树 平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。示例
- 输入: {1,2,3,4,5,6,7}
- 输出: true
解法
国庆快乐! 要思考怎么吧递归和子方法写出来!~public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return judge(root)!=-1;
}
//如果不是二叉平衡树,则直接返回-1结束
//如果是二叉平衡树,最后返回的是二叉平衡树的最大深度
public int judge(TreeNode root){
if(root == null){
return 0 ;
}
int leftDepth = judge(root.left);
int rightDepth = judge(root.right);
if(leftDepth == -1){
return -1;
}
if(rightDepth == -1){
return -1;
}
if(Math.abs(leftDepth-rightDepth)>1){
return -1;
}else{
return Math.max(leftDepth,rightDepth)+1;
}
}
}