#K14301. Construct a Full Binary Tree from a Sequence
Construct a Full Binary Tree from a Sequence
Construct a Full Binary Tree from a Sequence
You are given a sequence of n integers. Your task is to determine whether you can construct a full binary tree (i.e. every non-leaf node has exactly two children) using the given sequence when interpreted as a level-order traversal. Note that a full binary tree must have an odd number of nodes. In this problem, the binary tree is formed as a complete binary tree: for a node at index i (0-indexed), its left child is at index 2i+1 and its right child is at index 2i+2. If a child index goes out of bounds, that child is considered nonexistent and represented by -1.
More formally, given a sequence (b_0, b_1, \dots, b_{n-1}), if (n) is even, output "NO" because a full binary tree must satisfy (n = 2k+1) for some non-negative integer (k). Otherwise, construct the tree and compute its depth (the number of edges in the longest path from the root to a leaf). Then output:
- "YES" on the first line if the tree can be constructed.
- The depth of the tree on the second line.
- For each of the n nodes (in the same order as given in the input), output a line with three integers: the node value, the index of its left child, and the index of its right child (if a child does not exist, output -1).
If the tree cannot be constructed (i.e. n is even), simply output "NO".
Formula reminder: A full binary tree with (I) internal nodes has (2I+1) total nodes, i.e., (n=2I+1). ((n) must be odd.)
inputFormat
The first line contains an integer n, representing the number of nodes. The second line contains n space-separated integers denoting the sequence of node values.
outputFormat
If it is impossible to construct a full binary tree (i.e. if n is even), output a single line with the text "NO". Otherwise, output:
- The first line: "YES"
- The second line: an integer representing the depth of the tree
- The next n lines: each line contains three space-separated integers: the node value, the index of its left child, and the index of its right child (use -1 if the child does not exist)## sample
3
2 3 1
YES
1
2 1 2
3 -1 -1
1 -1 -1
</p>