</>CodexBash
Back to problems
Not started

Is the tree balanced

Easy
2000 ms limit256 MB memoryTrees

Stuck?

Show a hint

Return the height and the verdict together. Use -1 for a height to mean something below was already unbalanced, and let it travel up.

The idea behind this problem

A tree is balanced when, at every node, the heights of its two subtrees differ by at most one. Say whether the given tree is balanced.

Worked example#

3 9 20 null null 15 7:

      3
     / \
    9   20
       /  \
      15   7
nodeleft heightright heightdifference
9000
15000
7000
20110
3121

Nothing exceeds 1, so it is balanced.

Now 1 2 2 3 3 null null 4 4:

          1
        /   \
       2     2
      / \
     3   3
    / \
   4   4

At the root, the left side is 3 tall and the right is 1, a difference of 2. Not balanced.

Why "at every node" matters#

Checking only the root is not enough. A tree can have equal heights on each side of the root while one branch far below is badly lopsided. The definition is about every node, so the check has to be as well.

Doing it in one pass#

The slow way asks each node for its height, which recomputes the same heights over and over and costs O(n log n) at best and O(n squared) on a chain.

The better way makes one function return both answers at once: the height, and whether anything below was unbalanced. Use a height of -1 to mean "already unbalanced" and let it travel upward.

check(node):
    if node is missing, height 0
    left  = check(node.left);  if left is -1, return -1
    right = check(node.right); if right is -1, return -1
    if abs(left - right) > 1, return -1
    return 1 + max(left, right)

Every node is visited once, so O(n).

Constraints#

  • 0 <= number of nodes <= 5000
  • -10000 <= value <= 10000

Input

root is a count then that many level order tokens, null for a missing child.

Output

true or false.

Examples

Input

7
3 9 20 null null 15 7

Output

true

No node has sides differing by more than one.

Input

9
1 2 2 3 3 null null 4 4

Output

false

At the root the left side is three tall and the right is one.

Input

0

Output

true

An empty tree is balanced.

Something wrong with this problem? Report an issue

Ready to try it

Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.

Free, and it stays free. No card.