Skip to main content
All Questions

Balanced Tree

Medium
Unlock detailed company stats for this questionUpgrade

When using a tree data structure, it's common for the tree to become unbalanced over time due to the insertion order of nodes, which can in turn affect the performance of our programs. Let's define a balanced tree as one where the difference in height of the left and right subtrees is at most one, for all nodes in the given tree. Write a function is_balanced(node) that determines whether a binary tree is balanced or not.

Input: The root node of a binary tree

Output: True if the tree is balanced, False otherwise.

Assume you are given the root node of a tree that conforms to the following interface:

class Node { left: Node right: Node value: any }

Examples

Example 1: Balanced

Tree: a / \ b c / \ \ d e f is_balanced(a) # => True

Example 2: Balanced

Tree: a / \ b c \ d is_balanced(a) # => True

Example 3: Not Balanced

Tree: a / \ b c \ d \ e is_balanced(a) # => False

Example 4: Not Balanced

Tree: a / \ b c / \ d e / \ f g is_balanced(a) # => False

Note that while the last tree seems symmetrical, it is not balanced because nodes b and c are not balanced.

Related courses

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.

Course

System Design Interviews

Learn how to answer the latest system design questions across product, infrastructure, and AI domains. Features in-depth video examples, written breakdowns, and helpful reference patterns. Watch senior engineers and managers answer these questions in mock interview videos.