Closest Shared Mentor

Mediumdepth-first searchAlso known as Lowest Common Ancestor of a Binary Tree

A woodworking guild trains people by apprenticeship. The founder took on at most two apprentices, each of them later took on at most two of their own, and so on. The guild keeps this as a binary tree of membership numbers, with the founder at the root.

When two members disagree about technique, the guild asks the closest person in both of their training lines to settle it: the member furthest from the founder who trained both of them, directly or through others. If one of the two trained the other, that person settles it themselves.

Your task

Write closestSharedMentor(root, a, b). a and b are values of nodes in the tree. Return the value of their lowest common ancestor: the deepest node that has both a and b in its subtree. A node counts as being in its own subtree, so if a is an ancestor of b, the answer is a.

The tree is an ordinary binary tree, not a search tree: the numbers are in no particular order. All values are different, both a and b are in the tree, and they may be the same value. Trees are shown in level order with null for a missing child. Your function receives real TreeNode objects with val, left and right.

closestSharedMentor(root: TreeNode, a: int, b: int) → int

Examples

Example 1
Input
root = [8, 3, 11, 5, 1, 9, 14, null, null, 7, 4, null, null, 2, 6]
a = 7
b = 4
Output
1
Why

7 and 4 are both apprentices of 1. Member 3 and the founder 8 also trained both of them indirectly, but 1 is the closest, the deepest node that has both below it.

Example 2
Input
root = [8, 3, 11, 5, 1, 9, 14, null, null, 7, 4, null, null, 2, 6]
a = 1
b = 4
Output
1
Why

Member 1 trained member 4 directly. A member counts as being in their own line, so 1 settles it. The answer is not 3, the person above them.

Constraints

  • 1 ≤ number of members ≤ 1,000
  • -100,000 ≤ membership number ≤ 100,000, all different
  • a and b are both in the tree.
  • The tree is at most 500 levels deep.
Start with brute force

Find the path from the founder down to a, and separately the path down to b. Walk both paths together from the top; the last member they share is the answer.

That is O(n) and correct, but it walks the tree twice and stores two paths of up to 500 members. A trap to avoid: if you treat the tree as a search tree and go left or right by comparing numbers, you get wrong answers, because these numbers are not ordered. One bottom-up walk that reports what it found answers the question directly.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code