Skip to the code
cf.
+25 XP

#375 Is the Index Height-Balanced and Sorted?

medium

Before trusting a saved index, a client checks that it is a valid AVL tree. That means two things at once: it is a binary search tree (every left descendant strictly smaller and every right descendant strictly bigger than each node), and at every node the heights of the left and right subtrees differ by at most 1.

Write isAvlIndex(root) that returns true if both rules hold everywhere, and false otherwise. An empty tree is valid.

Example 1

Input: root = [20,10,30,5,15]
Output: true

It is sorted, and every node's two sides differ in height by at most one.

Example 2

Input: root = [1,null,2,null,3]
Output: false

Sorted, but the root's right side has height 2 and its left side 0.

Constraints

  • 0 <= number of nodes <= 10^4
  • -10^9 <= value <= 10^9

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).