剑指 Offer 55 - II. 平衡二叉树
思路
老样子
1.当前节点为根节点,是否平衡
2.左右节点为根节点,是否平衡
代码
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null)return true;
int l=dfs(root.left),r=dfs(root.right);
return (Math.abs(l-r)<=1)&&isBalanced(root.left)&&isBalanced(root.right);
}
public int dfs(TreeNode root){
if(root==null)return 0;
return 1+Math.max(dfs(root.left),dfs(root.right));
}
}