#C4991. Balance Spell

    ID: 48590 Type: Default 1000ms 256MiB

Balance Spell

Balance Spell

You are given a binary tree represented as a list of nodes. Each node is described by a triple \((v, l, r)\) where v is the node's value, and l and r are the values of the left and right child respectively. A value of 0 indicates that the child does not exist.

A tree is said to be balanced if for every node the difference between the heights of its left and right subtrees is at most 1, i.e.,

\[ |height_{left} - height_{right}| \le 1 \]

The spell can only transform a tree into a balanced tree if it is already balanced. Your task is to determine whether the given binary tree can be transformed into a balanced tree using the spell.

Print YES if the tree is balanced; otherwise, print NO.

inputFormat

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

  • The first line contains an integer n indicating the number of nodes in the tree.
  • The next n lines each contain three integers v l r representing a node, where v is the node's value, and l and r are the values of its left and right children respectively. A value of 0 indicates that the child is missing.

outputFormat

Output a single line to standard output (stdout) containing YES if the tree is balanced and can be transformed; otherwise, output NO.

## sample
3
1 2 3
2 0 0
3 0 0
YES