#K7641. Maximum Binary Tree Preorder Traversal
Maximum Binary Tree Preorder Traversal
Maximum Binary Tree Preorder Traversal
You are given an array of distinct integers. Your task is to construct the maximum binary tree and output its preorder traversal.
The maximum binary tree is defined recursively as follows:
If the array is empty, return null
(or equivalent). Otherwise, let \( m = \max(\text{nums}) \) be the maximum element and let its index be \( i \). Create a tree node with value \( m \). The left subtree is the maximum binary tree constructed from the subarray \( \text{nums}[0:i] \), and the right subtree is constructed from the subarray \( \text{nums}[i+1:] \).
After constructing the tree, perform a preorder traversal (visit the root, then left subtree, then right subtree) and output the sequence of node values separated by a single space.
inputFormat
The input consists of a single line containing a space-separated list of distinct integers.
Example: 3 2 1 6 0 5
outputFormat
Output a single line containing the preorder traversal of the constructed maximum binary tree. The values should be separated by a single space.
Example: 6 3 2 1 5 0
3 2 1 6 0 5
6 3 2 1 5 0