使用递归,
终止条件:穿过叶子结点,root == null;
子问题和问题的关系:左子树深度与右子树深度的差值小于1,并且左右子树也都为平衡二叉树
/** 递归,终止条件:穿过叶子结点,root == null; 子问题和问题的关系:左子树深度与右子树深度的差值小于1,并且左右子树也都为平衡二叉树
* 当前方法为 传入结点,返回该结点下的树是否为平衡二叉树*/
public boolean isBalanced(TreeNode root){
if (root == null){
return true;
}
return Math.abs(depth(root.left) - depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
/** 求出深度当前子树的深度,详见offer55_I*/
public int depth(TreeNode root){
if (root == null) return 0;
return Math.max(depth(root.left),depth(root.right)) + 1;
}

这篇博客探讨了如何使用递归方法判断一个二叉树是否为平衡二叉树,关键在于检查节点的左右子树深度差是否小于等于1,并确保每个子树也是平衡的。通过`isBalanced`函数实现,递归终止条件是到达叶子节点。

被折叠的 条评论
为什么被折叠?



