#K41762. Balanced Binary Tree Check
Balanced Binary Tree Check
Balanced Binary Tree Check
You are given a binary tree represented by m node triplets. Each triplet consists of a node value p and the values of its left (l) and right (r) children. A value of -1 indicates that the corresponding child does not exist. The tree is constructed with the first node in the input as the root.
A binary tree is said to be balanced if, for every node in the tree, the absolute difference between the heights of its left and right subtrees is at most 1. Formally, for every node, if \( h_L \) and \( h_R \) denote the heights of the left and right subtrees respectively, then the tree is balanced if \[ |h_L - h_R| \le 1 \] for all nodes.
Your task is to determine whether the given binary tree is balanced. Output YES
if it is balanced, and NO
otherwise.
inputFormat
The first line of input contains an integer m, representing the number of nodes in the tree. Each of the following m lines contains three space-separated integers: p, l, and r. Here, p is the value of the node, and l and r are the values of its left and right children respectively. A value of -1 indicates that the child does not exist.
outputFormat
Output a single line containing YES
if the binary tree is balanced, or NO
otherwise.
5
1 2 3
2 -1 -1
3 4 5
4 -1 -1
5 -1 -1
YES