LeetCode Solutions
110. Balanced Binary Tree
Time: $O(n\log n)$ Space: $O(h)$
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (root == nullptr)
return true;
return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 &&
isBalanced(root->left) && isBalanced(root->right);
}
private:
int maxDepth(TreeNode* root) {
if (root == nullptr)
return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 &&
isBalanced(root.left) &&
isBalanced(root.right);
}
private int maxDepth(TreeNode root) {
if (root == null)
return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
def maxDepth(root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(maxDepth(root.left), maxDepth(root.right))
return abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 and \
self.isBalanced(root.left) and self.isBalanced(root.right)