ð 110. 平衡äºåæ
2022幎10æ10æ¥
- algorithm
ð 110. 平衡äºåæ
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
// æè·¯ïŒ
// éåœ - æ±åœåèç¹å·Šå³åæ çé«åºŠå·®ïŒè¥åšèåŽå
ïŒæŽæ°æ倧é«åºŠ
return mySol(root) >= 0;
}
private int mySol(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return 0;
}
// root != null
int left = mySol(root.left);
if(left < 0) {
return -1;
}
int right = mySol(root.right);
if(right < 0) {
return -1;
}
if(Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
}