All problems

Problem 605

Minimum Absolute Difference in BST

Easy · 10 pts · Tree, Binary Search Tree, Depth-First Search

Problem

Given a binary search tree with at least two nodes and distinct values, find the minimum absolute difference between the values of any two different nodes. The nodes do not have to be adjacent in the tree. Because an in-order traversal visits the values in sorted order, the closest pair is always two consecutive values in that order, so one traversal that remembers the previous value is enough.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.

Output

Print the minimum absolute difference.

Constraints

2 <= number of nodes <= 10000; 0 <= value <= 100000; values are distinct

Example input

5
4 2 6 1 3

Example output

1

Explanation

The tree 4 2 6 1 3 holds the values 1, 2, 3, 4 and 6. In sorted order, neighbouring values differ by 1, 1, 1 and 2, so the minimum difference is 1.

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

Previous: Find Mode in Binary Search Tree Next: Convert BST to Greater Sum Tree