Skip to main content

Balanced Tree

MediumPremium

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.

We can calculate the depth (or height) of a tree by counting the number of nodes from the root to the leaf.

You might find it helpful to use recursion to traverse the nodes and find their height.

For every node, you should check whether the height of its subtrees meets the definition of being balanced.

How are you calculating the height of the tree? Does your function explore all paths?

Does your solution reject trees like the last example above?

Can you optimize the performance of your function? Can you find a linear time solution?