All problems

Problem 746

Inorder Successor in a BST

Medium · 20 pts · Tree, Binary Search Tree

Problem

Given a binary search tree with distinct values and a key K that is in the tree, find the in-order successor of K: the smallest value in the tree that is strictly greater than K. Print -1 if K is the largest value. Walk down from the root: whenever a node's value is greater than K it is a candidate and the search goes left to look for something smaller, otherwise the search goes right. This takes O(height) time.

Input

The first line contains K. The next two lines describe the BST: N, the number of tokens, then N level-order tokens with 'null' for missing children.

Output

Print the in-order successor of K, or -1.

Constraints

1 <= number of nodes <= 10000; values are distinct; K is in the tree

Example input

8
11
20 8 22 4 12 null null null null 10 14

Example output

10

Explanation

The BST 20 8 22 4 12 null null null null 10 14 holds 4 8 10 12 14 20 22 in order. The value after 8 is 10, so for K = 8 the answer is 10.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Insert into a Binary Search Tree Next: Recover a Binary Search Tree