#BST0000002. Chèn dãy khóa vào BST (Insert a Key Sequence into a BST)
Chèn dãy khóa vào BST (Insert a Key Sequence into a BST)
Insert a Key Sequence into a BST
Source: Phuoc Hung OJ
Version: Phuoc Hung OJ Extended
Problem Statement
Initially the binary search tree (BST) is empty. Process in order:
- If the tree is empty, the inserted key becomes the root.
- At a node with key , continue to the left child if and to the right child if .
- If the required child is empty, create a new node with key there.
- If at an existing node, ignore this insertion; the BST stores no additional copy of a duplicate key.
After all insertions, describe the resulting tree using two traversals:
- preorder: root, left subtree, right subtree;
- inorder: left subtree, root, right subtree.
Input
The first line contains .
If , the next line contains signed integers in insertion order. If , there is no key line.
Output
The first line contains the preorder traversal.
The second line contains the inorder traversal.
Separate keys on the same line by one space. If the tree is empty, print EMPTY on both lines.
Subtasks
Subtask 1 (20 points): .
Subtask 2 (30 points): .
Subtask 3 (50 points): .
In all subtasks, every is a signed 64-bit integer: . Duplicate keys are ignored.
Examples
Input
7
8 3 10 1 6 14 4
Output
8 3 1 6 4 10 14
1 3 4 6 8 10 14
Explanation
Key becomes the root. Keys and become its left and right children, and the remaining keys are inserted according to the same rule.
Preorder visits the root first and gives 8 3 1 6 4 10 14. Inorder visits left subtree, root, then right subtree and gives 1 3 4 6 8 10 14.