Problems/Trees/Balanced Binary Tree Validation
Trees
easy

Balanced Binary Tree Validation

Determine if a binary tree is considered 'well-proportioned' - meaning that for every node, the heights of its left and right subtrees are within a certain tolerance. This is a common tree problem that tests your understanding of recursion and tree traversals.

treerecursiondepth-first searchbinary tree

Problem Statement

Given the root of a binary tree and a maximum allowed height difference, determine if the tree is 'well-proportioned'. A binary tree is well-proportioned if, for every node in the tree, the absolute difference in height between its left and right subtrees is less than or equal to the given maximum allowed difference. Return True if the tree is well-proportioned, and False otherwise.

Example 1
Input: root = [3,9,20,null,null,15,7], max_difference = 1
Output: True
The tree is well-proportioned because for each node, the absolute difference in height between its left and right subtrees is at most 1.
Example 2
Input: root = [1,2,2,3,3,null,null,4,4, null, null, null, null, 5,5], max_difference = 1
Output: False
The tree is not well-proportioned. The node with value 2 on the second level has a left subtree of height 3 and a right subtree of height 0. The absolute difference is 3, which is greater than the maximum allowed difference of 1.
Constraints
  • -The number of nodes in the tree is in the range [0, 10000].
  • -Node.val is in the range [-1000, 1000].
  • -max_difference is in the range [0, 100].

Brute Force Approach

The brute force approach involves calculating the height of the left and right subtrees for every node in the tree. For each node, we would recursively compute the height of both subtrees and check if the difference exceeds the maximum allowed difference. If it does, we know the tree is not well-proportioned. Like inspecting every item in a warehouse for defects one by one, this is simple but inefficient. This approach has a time complexity of O(n^2) because for each node, we are potentially traversing the entire subtree to calculate its height. The space complexity is O(n) in the worst case, due to recursion depth.

TimeO(n^2)
SpaceO(n)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem