#K53452. Balanced Binary Tree Check

    ID: 29534 Type: Default 1000ms 256MiB

Balanced Binary Tree Check

Balanced Binary Tree Check

You are given the level-order representation of a binary tree. Your task is to determine whether the tree is height-balanced. A binary tree is considered balanced if for every node, the absolute difference of the heights of its left and right subtrees is at most \(1\), i.e., \(|\text{height(left)} - \text{height(right)}| \le 1\).

The tree is provided in level-order where "null" represents a missing node. The input begins with an integer \(T\) denoting the number of test cases. Each test case is given in a new line as a sequence of space-separated values representing the tree in level order.

For each test case, print 1 if the tree is balanced and 0 otherwise.

inputFormat

The input is read from standard input (stdin) and is formatted as follows:

  • The first line contains an integer \(T\), the number of test cases.
  • The following \(T\) lines each contain a level-order traversal of the binary tree with space-separated tokens. Each token is either an integer (the node value) or the string "null" indicating a missing node.

Note: The tree can be empty. In that case, the line will contain "null".

outputFormat

For each test case, output a single integer in a new line: 1 if the binary tree is balanced, and 0 otherwise. The output is written to standard output (stdout).

## sample
5
1 2 3 4 5
1 2 null 3
1 2 3 4 null null null 5
1
null
1

0 0 1 1

</p>