#K39252. Balanced Binary Tree Rearrangement
Balanced Binary Tree Rearrangement
Balanced Binary Tree Rearrangement
You are given a list of integers representing the nodes of a binary tree. Your task is to determine whether it is possible to rearrange these nodes to form a balanced binary tree.
A balanced binary tree is one in which the depths of the two subtrees of every node differ by no more than one. In this problem, we use a related concept based on a complete binary tree. Given n nodes, the height h of a complete binary tree is computed as:
$$h = \lceil \log_{2}(n+1) \rceil - 1$$
The total number of nodes in a complete binary tree of height h is:
$$\text{complete\_nodes} = 2^{h+1} - 1$$
If the difference between complete_nodes
and n is not more than \(2^{h}\), then it is possible to rearrange the nodes to form a balanced binary tree. In such a case, print Yes
; otherwise, print No
.
inputFormat
The first line contains a single integer n representing the number of nodes.
The second line contains n space-separated integers which represent the node values.
outputFormat
Output a single line with either Yes
if the nodes can be rearranged to form a balanced binary tree, or No
otherwise.
5
1 2 3 4 5
Yes