判断平衡二叉树
题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210217130940374.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzA0NTI4,size_16,color_FFFFFF,t_70)
解题思路
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210217130956595.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzA0NTI4,size_16,color_FFFFFF,t_70)
代码示例
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
if(root.left==null&&root.right==null){
return true;
}
if(maxDepth(root)<=2){
return true;
}
return Math.abs(maxDepth(root.left)-maxDepth(root.right))<=1&&isBalanced(root.left)&&isBalanced(root.right);
}
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}else if(root.left==null&&root.right==null){
return 1;
}else {
int leftheight=maxDepth(root.left);
int rightheight=maxDepth(root.right);
return Math.max(leftheight, rightheight)+1;
}
}
}