A records office stores every document's call number in a binary search tree: for any node, every call number in its left subtree is strictly smaller than the node's own call number, and every call number in its right subtree is strictly larger. A clerk keeps a single cursor over this tree, positioned initially just before the smallest call number in the whole archive. The clerk repeatedly issues one of four commands: step forward to the next larger call number, step back to the next smaller one, or simply ask (without moving) whether stepping in either direction is currently possible. Process the clerk's commands in order and report the result of each one.
t, the number of tokens in a level-order (breadth-first) serialization of the tree, counting both value tokens and null placeholders for missing children.t space-separated tokens. The first token is the root's call number. After that, treat the already-emitted nodes as a queue in the order they were introduced: for each node popped from that queue, its next unread token is its left child and the token after that is its right child, where each of those two tokens is either an integer or the literal null (meaning that child does not exist and is not pushed onto the queue).q, the number of commands.q lines contains exactly one command: NEXT, PREV, HASNEXT, or HASPREV.Print q lines, one per command, in the order the commands were given:
NEXT — move the cursor to the next larger call number and print it.PREV — move the cursor to the next smaller call number and print it.HASNEXT — print true if a NEXT move is currently possible, otherwise false. This never moves the cursor.HASPREV — print true if a PREV move is currently possible, otherwise false. This never moves the cursor.It is guaranteed that a NEXT command is only ever issued when HASNEXT would currently report true, and a PREV command is only ever issued when HASPREV would currently report true. HASNEXT and HASPREV may be issued at any point, including before any move has been made, and must simply report the correct boolean.
Example 1
Input
11 4 2 6 1 3 null null null null null null 6 NEXT NEXT HASPREV PREV HASNEXT NEXT
Expected
1 2 true 1 true 2
Explanation
The tree has call numbers {1,2,3,4,6} whose sorted order is 1,2,3,4,6. NEXT->1, NEXT->2. HASPREV is now true (there is a value before the current position). PREV->1 (back to the smallest). HASNEXT is true (2,3,4,6 still remain ahead). NEXT->2 again.
Example 2
Input
1 7 3 HASNEXT NEXT HASNEXT
Expected
true 7 false
Explanation
The tree has a single call number, 7. Before any move, HASNEXT is true since 7 is still ahead of the cursor. NEXT moves onto it and prints 7. Now there is nothing further ahead, so the final HASNEXT is false.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →