Given a binary tree, determine if it is height-balanced.
A height-balanced binary tree is defined as:
True
if the tree is height-balanced, otherwise False
.True
.To determine if a binary tree is height-balanced, we can use a recursive approach. The idea is to check the heights of the left and right subtrees of every node and ensure the difference is no more than 1.
Base Case: If a node is None
(i.e., we have reached a leaf node’s child), it is considered balanced with a height of 0.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def check_balance_and_height(node):
# Base case: an empty subtree is balanced and has height 0
if not node:
return True, 0
# Check left subtree
left_balanced, left_height = check_balance_and_height(node.left)
if not left_balanced:
return False, 0
# Check right subtree
right_balanced, right_height = check_balance_and_height(node.right)
if not right_balanced:
return False, 0
# Current node's balance check
balanced = abs(left_height - right_height) <= 1
height = max(left_height, right_height) + 1
return balanced, height
is_balanced, _ = check_balance_and_height(root)
return is_balanced
The time complexity of this solution is (O(N)), where (N) is the number of nodes in the tree. This is because each node in the tree is visited once.
The space complexity is (O(H)) where (H) is the height of the tree. This is due to the recursion stack. In the worst case, the height of the tree could be (O(N)) (for a completely unbalanced tree), but on average for a balanced tree, it would be (O(\log N)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?