🌟坚持每日刷算法,😃将其变为习惯🤛让我们一起坚持吧💪
题目链接:110. 平衡二叉树
分析
首先,明确平衡二叉树条件,一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
那么我们就直接可以求出节点的高度,然后计算高度差,从而判断是否平衡
注意: 要去绝对值之后比较高度差是否大于1哦
逐步解决
- 求高度差,对于二叉树来说,当然是递归啦,使用后序遍历
public int getDepth(TreeNode root){
if(root == null) return 0;
return Math.max(1 + getDepth(root.left), 1 + getDepth(root.right));
}
- 递归判断平衡
if(root==null) return true;
if(Math.abs((getDepth(root.left) - getDepth(root.right)) )> 1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
完整代码
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
if(Math.abs((getDepth(root.left) - getDepth(root.right)) )> 1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
public int getDepth(TreeNode root){
if(root == null) return 0;
return Math.max(1 + getDepth(root.left), 1 + getDepth(root.right));
}
}