原题地址:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/
题目描述:

代码:
递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
if(isBalanced(root.left) == true && isBalanced(root.right) == true && Math.abs(depth(root.left) - depth(root.right)) <= 1) return true;
return false;
}
public int depth(TreeNode root)
{
if(root == null) return 0;
return Math.max(depth(root.left), depth(root.right)) + 1;
}
}
本文详细解析了如何使用递归算法判断一棵二叉树是否为平衡二叉树,通过计算每个节点的左右子树深度并比较其差值,确保整棵树的平衡性。
2093

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



