Closest Shared Mentor

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

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

When two members disagree on technique, the closest person in both training lines settles it. That person is the member furthest from the founder who trained both of them, directly or through others. If one of them trained the other, that one settles it.

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 with both a and b in its subtree. A node is 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 founder 8 also trained both indirectly, but 1 is the deepest node with 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, and a member counts as being in their own line, so member 1 settles it, and not member 3 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 to a, and the path to b. Walk down both paths together from the top, and the last member they have in common is the answer.

That is O(n) and correct, but it walks the tree twice and stores two paths of up to 500 members. Do not treat the tree as a search tree by going left or right based on comparing numbers, because these numbers are not ordered and the answers would be wrong. A single bottom-up walk finds the answer 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