Balanced Binary Tree
easy
binary-tree
depth-first-search
recursion
Given the root of a binary tree, return true if the tree is height-balanced, or false otherwise.
A binary tree is height-balanced when, for every node, the heights of its left and right subtrees differ by no more than 1.
Input / output
- Input:
root: TreeNode(JSON test fixture is a LeetCode-style level-order array usingnullfor missing children, for example[3,9,20,null,null,15,7]) - Output:
boolean
Examples
root = [3,9,20,null,null,15,7]returnstrue.root = [1,2,2,3,3,null,null,4,4]returnsfalse.root = []returnstruebecause an empty tree is balanced.
Constraints
0 <= number of nodes <= 5000-10^4 <= Node.val <= 10^4
Follow-up Can you compute balance and height in the same postorder traversal so you never recompute subtree heights twice?
Examples
Example 1
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3
Input: root = []
Output: true
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.