Skip to content
BytePatterns

Distance Between Two BST Keys

MediumTrees & BST#bst#lowest-common-ancestor~25m

Problem

A binary search tree stores distinct keys, and two of its keys a and b are given, both guaranteed to be in the tree. Return the number of edges on the path that connects the node holding a to the node holding b. When a equals b the answer is 0.

Examples

Input:  tree = 8, left 3 with children 1 and 6 (6 has children 4 and 7),
        right 10 with a right child 14; a = 4, b = 14
Output: 5
Why:    the path is 4, 6, 3, 8, 10, 14
Input:  same tree; a = 6, b = 7
Output: 1
Why:    7 is a child of 6
Input:  same tree; a = 10, b = 10
Output: 0
Why:    edge case, a node is zero edges from itself

Hints

0 / 3

Stuck on the idea rather than the code? Lowest Common Ancestor covers it.