Write an efficient algorithm to determine if a binary tree satisfies the height-balanced property of the red–black tree or not.

The red–black tree’s height-balanced property states that the path from the root to the farthest leaf is no more than twice as long as a path from the root to the nearest leaf. In other words, the maximum height of any node in a tree is not greater than twice its minimum height.

 
For example, the following tree is height-balanced:

Height Balanced Tree

In contrast, the following tree violates the red–black tree property at node 3:

Height Unbalanced Tree

Practice this problem

A simple solution would be to calculate the maximum and minimum height of every node in the tree and determine if the subtree rooted at that node is balanced or not. If the height-balanced property is satisfied for every subtree, the binary tree enforces the red–black tree’s height-balanced property. For a tree containing n elements, this solution takes O(n2) time since, for every node, we are traversing the whole subtree rooted at that node.

 
The main challenge is to perform this in a single tree traversal, i.e., in O(n) time. The idea is to perform a postorder traversal on the binary tree and calculate the maximum and minimum height for every node in a bottom-up fashion. Then we can easily check if the height-balanced property of the red–black tree is satisfied for every node in the tree or not.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Height-balanced

Java


Download  Run Code

Output:

Height-balanced

Python


Download  Run Code

Output:

Height-balanced

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(h) for the call stack, where h is the height of the tree.