Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-075

Balanced Binary Tree Check

Problem

Check whether a binary search tree built from the given values is height-balanced.

Insert values in order (duplicates ignored). A tree is balanced when, for every node, the heights of its left and right subtrees differ by at most one. Compute heights with a post-order recursion that reports failure early by returning -1.

Return True if balanced, otherwise False. An empty tree is balanced.

Hint

Return -1 from the height recursion as soon as any subtree is unbalanced.

Test cases

case 1
in: [[1,2,3]]
expected: false
case 2
in: [[5,3,8,2]]
expected: true
case 3
in: [[]]
expected: true
case 4
in: [[2,1,3]]
expected: true
case 5
in: [[10,5,15,3,7,12,20]]
expected: true
Starter codePython
def is_balanced_tree(values):
    # Your code here
    pass

5 test cases · run your code against them in the editor