All problems

Problem 154

Kth Smallest Element in a BST

Medium · 20 pts · Tree, Binary Search Tree, Depth-First Search

Problem

You are given a binary search tree with distinct values and a number K. Print the K-th smallest value in the tree, counting from 1. An inorder traversal of a binary search tree visits the values in increasing order, so the K-th node visited by the inorder traversal is the answer. You can stop the traversal as soon as you reach it.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses). Third line: integer K.

Output

Print the K-th smallest value.

Constraints

1 <= K <= number of nodes <= 10000; -10^4 <= value <= 10^4; values are distinct

Example input

5
3 1 4 null 2
1

Example output

1

Explanation

The tree has root 3, left child 1 (with right child 2) and right child 4. Its values in increasing order are 1 2 3 4, and the 1st smallest is 1.

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

Previous: Lowest Common Ancestor of a BST Next: Binary Tree Right Side View