Skip to main content

Recursive Balanced Tree Validator

easy
TreeBinary TreeRecursionDepth First SearchDfs RecursiveDp On Trees
Asked atAmazonMicrosoftGoogleMeta

Problem Description

A binary tree is considered **height-balanced** if, for every node in the tree, the heights of its left and right subtrees differ by at most 1.

Given the root of a binary tree, return `true` if it is height-balanced, and `false` otherwise. Implement your solution using recursion.

**Example 1:**
```
Input: root = [4, 2, 6, 1, 3, 5, 7]
Output: true
```
*This is a complete binary tree — all subtrees are balanced.*

**Example 2:**
```
Input: root = [1, 2, null, 3, null, null, null, 4]
Output: false
```
*The left subtree has height 3 while the right subtree has height 0.*

Constraints

  • The number of nodes in the tree is in the range [0, 5000].
  • Node values are integers in the range [-10^4, 10^4].

Follow-up

Can you solve this problem using an iterative post-order traversal with an explicit stack instead of the call stack?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.