AcWing 72. 平衡二叉树
原题链接
简单
作者:
小轩喵灬
,
2025-01-11 18:10:08
,
所有人可见
,
阅读 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private boolean isBalanced = true;
public boolean isBalanced(TreeNode root) {
height(root);
return isBalanced;
}
private int height(TreeNode root) {
if (root == null || !isBalanced) {
return 0;
}
int left = height(root.left);
int right = height(root.right);
if (Math.abs(left - right) > 1) {
isBalanced = false;
}
return 1 + Math.max(left, right);
}
}