#K94512. Balanced Binary Tree Checker

    ID: 38658 Type: Default 1000ms 256MiB

Balanced Binary Tree Checker

Balanced Binary Tree Checker

You are given a binary tree with n nodes. Each node is described by three integers: its value and two indices indicating the left and right child respectively. A value of -1 indicates that the corresponding child does not exist.

A binary tree is said to be balanced if for every node, the absolute difference between the heights of its left and right subtrees is at most 1. The height of an empty tree is defined as 0.

Your task is to determine whether the given binary tree is balanced or not.

Note: The tree nodes are given in order from index 1 to n, and the root of the tree is the node with index 1.

The balance condition can also be written in LaTeX as:

\( |h(\text{left}) - h(\text{right})| \le 1 \)

inputFormat

The input is read from stdin and has the following format:

n
value1 left1 right1
value2 left2 right2
... 
valuen leftn rightn

Where n is the number of nodes, and for each node:

  • value is the node's value.
  • left is the index of the left child (or -1 if no left child).
  • right is the index of the right child (or -1 if no right child).

outputFormat

Print to stdout a single line: True if the binary tree is balanced, or False otherwise.

## sample
3
1 2 3
2 -1 -1
3 -1 -1
True