#K74742. Magic Tree
Magic Tree
Magic Tree
You are given a binary tree, and your task is to determine whether it is a Magic-Tree. A Magic-Tree is defined as a binary tree in which all root-to-leaf paths have the same sum. In other words, if you calculate the sum of the node values along each path from the root to any leaf, all sums should be equal.
The binary tree is provided in the following format: each node is described by a triplet of integers (value, left_index, right_index). The value represents the node's value, while left_index and right_index represent the indices of the node's left and right children respectively. An index of -1
means that the corresponding child does not exist. The root of the tree is always at index 0.
If the tree is empty (i.e. there are no nodes), consider it a Magic-Tree.
Your program should process multiple test cases. For each test case, read the description of the tree, determine if it is a Magic-Tree, and print "YES" if it is, otherwise print "NO".
inputFormat
The input is read from standard input (stdin) and has the following format:
T n_1 value left_index right_index value left_index right_index ... (n_1 lines) n_2 value left_index right_index ... (n_2 lines) ...
Here, T
denotes the number of test cases. For each test case, the first line contains an integer n
, the number of nodes in the binary tree. This is followed by n
lines where each line contains three space-separated integers representing a node's value
, and the indices of its left and right children. If a child does not exist, the corresponding index will be -1
.
outputFormat
For each test case, output a single line to standard output (stdout) containing either "YES" if the binary tree is a Magic-Tree, or "NO" otherwise.
## sample5
0
1
5 -1 -1
3
10 1 2
5 -1 -1
5 -1 -1
3
10 1 2
5 -1 -1
7 -1 -1
4
8 1 2
3 3 -1
5 -1 -1
2 -1 -1
YES
YES
YES
NO
YES
</p>