LeetCode 110. 平衡二叉树
原题链接
简单
作者:
caichuntao
,
2023-06-26 16:24:43
,
所有人可见
,
阅读 93
方法1:自上而下递归
时间复杂度:O(n2)
空间复杂度:O(n)
解题思路
https://leetcode.cn/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/
Java 代码
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
if (Math.abs(height(root.left) - height(root.right)) > 1) {
return false;
} else {
return isBalanced(root.left) && isBalanced(root.right);
}
}
public int height(TreeNode node) {
if (node == null) {
return 0;
} else {
return Math.max(height(node.left), height(node.right)) + 1;
}
}
}