#K70347. Balanced Binary Tree Check

    ID: 33288 Type: Default 1000ms 256MiB

Balanced Binary Tree Check

Balanced Binary Tree Check

You are given a binary tree represented as a level-order traversal list. The tree is considered height-balanced if, at every node, the absolute difference between the heights of its left subtree and right subtree is at most 1. In other words, for every node, if the height of the left subtree is \(h_L\) and the height of the right subtree is \(h_R\), then the tree is balanced if \(|h_L - h_R| \leq 1\).

The binary tree is provided as a list of integers. The position of each integer corresponds to its position in a breadth-first (level-order) traversal. A value of -1 indicates a missing node. Note that an empty tree is considered balanced.

Your task is to determine whether the given binary tree is height-balanced. Output 1 if it is balanced, or 0 if it is not.

inputFormat

The input is given via standard input (stdin) in the following format:

  1. The first line contains an integer n representing the number of elements in the tree list.
  2. If n > 0, the second line contains n space-separated integers representing the binary tree in level-order. A value of -1 denotes a missing node. If n = 0, the tree is empty.

outputFormat

Output a single line via standard output (stdout) containing 1 if the binary tree is height-balanced, or 0 otherwise.

## sample
9
1 2 2 3 3 -1 -1 4 4
0

</p>