Balanced Binary Tree
Time
Space
Problem
Section titled “Problem”Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”A tree is height-balanced if, at every node, the heights of the left and right subtrees differ by at most one. Computing the height separately for each node would repeat work. A post-order traversal computes each child’s height first, so the node’s own height and balance check take constant extra work.
Algorithm
Section titled “Algorithm”- Set
ans = trueand calltraverse(root). - In
traverse, return for a null node; otherwise recurse into the left and right children first. - Store the node’s height in the map
mp, starting at0for a leaf. For each existing child, updatemp[root]tomp[child] + 1. - Use
diffto hold the left heightmp[root->left] + 1minus the right heightmp[root->right] + 1, with a missing child counting as0. - If
abs(diff) > 1, setans = false. - Return
ans.
Complexity
Section titled “Complexity”- Time: — every node is visited once, but each access to the ordered
mapcosts . - Space: — the map stores one height per node; the recursion stack adds .
Edge cases
Section titled “Edge cases”- Empty tree:
traversereturns at once and the answer istrue.
class Solution { bool ans; map<TreeNode*, int> mp;
public: void traverse(TreeNode* root) { if (!root) return; traverse(root->left); traverse(root->right); mp[root] = 0; int diff = 0; if (root->left) { mp[root] = max(mp[root], mp[root->left] + 1); diff = mp[root->left] + 1; } if (root->right) { mp[root] = max(mp[root], mp[root->right] + 1); diff -= mp[root->right] + 1; } diff = abs(diff); if (diff > 1) ans = false; }
bool isBalanced(TreeNode* root) { ans = true; traverse(root); return ans; }};Give it a try first
Attempt the problem on LeetCode — the code will still be here.