Build a ternary search tree with an array of distinct positive integers.
Task Description
You are given an array of N unique and positive integers. Please convert the array into a ternary search tree.
Each node of a ternary search tree stores at most two integers -- the smaller S and the larger L. Each node has three pointers, left, mid, and right, and each pointer points to a subtree. All integers in the left subtree are smaller than S, all integers in the mid subtree are larger than S and smaller than L, and all integers in the right subtree are larger than L. Note that if a node stores only one integer k, you need to store it as the larger one, and set the small one to -1.
When the integer sequence is {9, 5, 2, 7}, we build the ternary tree as follows. Note that all pointers that do not link to any node must be set to NULL.
The input contains only one test case. The first line contains one integers N, representing the number of sequence. The second line contains N integers, s0, s1, … , sn-1, representing the value of index.
N < 32768
Output Format
Print all the values of nodes in the tree by pre-ordering, and each node in a line.
Build a ternary search tree with an array of distinct positive integers.
Task Description
You are given an array of N unique and positive integers. Please convert the array into a ternary search tree.
Each node of a ternary search tree stores at most two integers -- the smaller S and the larger L. Each node has three pointers, left, mid, and right, and each pointer points to a subtree. All integers in the left subtree are smaller than S, all integers in the mid subtree are larger than S and smaller than L, and all integers in the right subtree are larger than L. Note that if a node stores only one integer k, you need to store it as the larger one, and set the small one to -1.
When the integer sequence is {9, 5, 2, 7}, we build the ternary tree as follows. Note that all pointers that do not link to any node must be set to NULL.
figure
We define a tree node as follows.
Please write a function to construct the ternary tree. The prototype of the function is as followed.
You may use the following main function to test your program.
The construct.h is as followed.
Subtasks
Input Format
The input contains only one test case. The first line contains one integers N, representing the number of sequence. The second line contains N integers, s0, s1, … , sn-1, representing the value of index.
Output Format
Print all the values of nodes in the tree by pre-ordering, and each node in a line.
Sample Input 1
Sample Output 1
Sample Input 2
Sample Output 2
Sample Input 3
Sample Output 3
Sample Input 4
Sample Output 4