




Sponsored
Sponsored
This approach involves recursively calculating the height of each subtree and checking if the subtrees are balanced by ensuring the difference in height is not more than one.
Time Complexity: O(N^2), where N is the number of nodes in the tree, as we recalculate the height of subtrees multiple times. Space Complexity: O(N) due to recursion stack.
1class TreeNode:
2    def __init__(self, x):
3        self.val = x
4        self.left = None
5        self.right = None
6
7class Solution:
8    def isBalanced(self, root: TreeNode) -> bool:
9        if not root:
10            return True
11
12        def height(node):
13            if not node:
14                return 0
15            return max(height(node.left), height(node.right)) + 1
16
17        left_height = height(root.left)
18        right_height = height(root.right)
19
20        if abs(left_height - right_height) > 1:
21            return False
22
23        return self.isBalanced(root.left) and self.isBalanced(root.right)This Python implementation utilizes a nested helper function height to calculate the height of each node’s subtrees. The primary function isBalanced checks if the balance criteria are satisfied recursively.
This optimized approach calculates the height and balance status of a tree in a single recursive function, thus avoiding recalculations by returning both height and balanced status in form of tuples or objects.
Time Complexity: O(N). Space Complexity: O(N), which includes the recursion stack depth.
1#
We use a helper struct Result holding both height and balanced state. The checkBalance function recurses over nodes, aggregating this data, and halting early if imbalance is detected.