Problem 431964 · easy · Level 04 Non-Linear Data Structures

The Key That Comes Next Inside the Subtree

binary search trees · successor · traversal

The symmetric successor of a node is the smallest key in its right subtree: one step right, then left as far as you can go. It is the key that would take the node's place if the node were removed, because it is the smallest key still larger than it.

Write symmetric_successor(root, value) returning that key for the node holding value, or -1 when that node has no right subtree. The tree is a search tree with distinct keys, and value is always in it.

Examples

Input:  root = build_tree([20, 10, 30, 5, 15, 25, 40]), value = 20
Output: 25
Explanation: one step right to 30, then left to 25.

Input:  root = build_tree([20, 10, 30, 5, 15, 25, 40]), value = 5
Output: -1
Explanation: 5 is a leaf, so it has no right subtree.

Constraints

  • 1 <= number of nodes <= 10**5, keys are distinct integers
  • A node whose own successor lies above it in the tree still answers -1; only the right subtree counts.

Goals

  • Find the smallest key of a right subtree by going left as far as possible
  • Tell the symmetric successor apart from the in-order successor of the whole tree
  • Report that there is none when the right subtree is empty
Starting Python…