A regional distribution warehouse organizes its storage bins in a binary search tree keyed by bin code, so pickers can locate any bin quickly by comparing codes as they descend from the root. Warehouse safety auditors worry that two bins with very close codes could be mixed up during a rushed pick, so they want to know the smallest possible difference between the codes of any two distinct bins in the facility.
You are given the tree's structure as a list of nodes. Each node has a unique integer bin code and, other than leaf nodes, pointers to its left and right child nodes; the ordering of the tree obeys the binary search tree property (every code in a left subtree is smaller than its node's code, and every code in a right subtree is larger). Determine the minimum absolute difference between the bin codes of any two distinct bins in the warehouse.
n, the number of bins (nodes) in the tree.n lines describes one node as four integers id value left right, where id is the node's index (0-indexed), value is its bin code, and left/right are the indices of its left and right child nodes, or -1 if that child does not exist. The node with id = 0 is always the root.Print a single integer: the minimum absolute difference between the bin codes of any two distinct bins.
n nodes, rooted at id 0.Example 1
Input
5 0 4 1 2 1 2 3 4 2 6 -1 -1 3 1 -1 -1 4 3 -1 -1
Expected
1
Explanation
The tree has root bin 4 (id 0) with left child bin 2 (id 1) and right child bin 6 (id 2); bin 2 has children bin 1 (id 3) and bin 3 (id 4). Reading the bin codes in sorted (inorder) order gives 1, 2, 3, 4, 6. The gaps between consecutive codes are 1, 1, 1, 2, so the smallest difference between any two bins is 1.
Example 2
Input
3 0 1 -1 1 1 3 2 -1 2 2 -1 -1
Expected
1
Explanation
The tree has root bin 1 (id 0) with right child bin 3 (id 1), which itself has left child bin 2 (id 2). Sorted in order, the codes are 1, 2, 3, with gaps 1 and 1, so the minimum difference is 1.
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 →