#BST0000022. Bộ lặp cây tìm kiếm nhị phân (Binary Search Tree Iterator)
Bộ lặp cây tìm kiếm nhị phân (Binary Search Tree Iterator)
Binary Search Tree Iterator
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
Build a BST from the distinct keys in insertion order. Consider its inorder sequence: the keys obtained by visiting left subtree, root, then right subtree.
An iterator initially points to a position before the first element of this inorder sequence. Process commands in order:
N represents next(): move the iterator to the next inorder element and print that key.
H represents hasNext(): print whether an element still exists after the current iterator position. This command does not move the iterator.
Every N command is guaranteed to be valid, so at least one next element exists whenever N is issued.
Input
The first line contains .
The second line contains the distinct keys .
The third line contains .
Each of the next lines contains exactly one character, N or H.
Output
Every command produces exactly one output line.
For N, print the key returned by next().
For H, print lowercase true if a next element exists, otherwise lowercase false.
Subtasks
Subtask 1 (20 points): .
Subtask 2 (30 points): .
Subtask 3 (50 points): .
In all subtasks, , all are distinct, and every N command is valid.
Examples
Input
5
7 3 15 9 20
10
N
N
H
N
H
N
H
N
H
H
Output
3
7
true
9
true
15
true
20
false
false
Explanation
The inorder sequence is . The first two N commands move to and .
There is still a next element after , so H prints true. Later N commands return , , and . Once the iterator reaches , no element remains, so the final two H commands both print false; calling H does not change the iterator position.