class Node: def __init__(self, val): self.val = val self.left = None self.right = None def is_balanced(root): def height(node): if not node: return 0 left_height = height(node.left) right_height = height(node.right) if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1: return -1 return max(left_height, right_height) + 1 return height(root) != -1 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.left.left = Node(6) print(is_balanced(root))
The tree is not balanced because the left subtree of the root has height 3 while the right subtree has height 1, difference is more than 1.
The function returns False.
A balanced binary tree means for every node, the height difference between its left and right subtree is at most 1.
def is_balanced(root): def height(node): if node is None: return 0 left_height = height(node.left) right_height = height(node.right) if abs(left_height - right_height) > 1: return False return max(left_height, right_height) + 1 return height(root)
The height function returns False (a boolean) when imbalance is detected, but returns int otherwise. This mixes types and causes the final return to be an int or False, not a boolean indicating balance.
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def is_balanced(root): def height(node): if not node: return 0 left_height = height(node.left) right_height = height(node.right) if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1: return -1 return max(left_height, right_height) + 1 return height(root) != -1 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) print(is_balanced(root))
The tree is perfect and balanced, so the function returns True.
Post-order traversal allows checking left and right subtrees first, then current node, enabling balance check and size tracking efficiently.
