#K75777. Height-Balanced Binary Tree

    ID: 34495 Type: Default 1000ms 256MiB

Height-Balanced Binary Tree

Height-Balanced Binary Tree

You are given a binary tree represented by a list of nodes. Each node is described by three integers: the node's value, the value of its left child, and the value of its right child. A value of -1 indicates that the child is absent.

A binary tree is said to be height-balanced if for every node in the tree, the difference in height between its left and right subtrees is at most \(1\). Formally, for every node \(v\), if \(h_L\) is the height of the left subtree and \(h_R\) is the height of the right subtree, then the tree is height-balanced if:

\(|h_L - h_R| \le 1\)

Your task is to determine whether the given binary tree is height-balanced. The tree is provided in the following format:

  • The first line contains an integer \(n\) representing the number of nodes.
  • The next \(n\) lines each contain three space-separated integers \(u\), \(v\), and \(w\), where \(u\) is the node's value, and \(v\) and \(w\) are the values of its left and right children respectively (a value of -1 indicates a missing child). The first node given is always the root of the tree.

Output YES if the tree is height-balanced, otherwise output NO.

inputFormat

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

  • The first line contains a single integer \(n\), the number of nodes in the tree.
  • The following \(n\) lines each contain three space-separated integers \(u\), \(v\), and \(w\). Here, \(u\) represents the node's value; \(v\) represents the value of the left child; and \(w\) represents the value of the right child. A value of -1 indicates that the corresponding child does not exist.

outputFormat

Output to standard output (stdout) a single line containing YES if the binary tree is height-balanced; otherwise, print NO.

## sample
3
1 2 3
2 -1 -1
3 -1 -1
YES