Skip to the code
cf.
+10 XP

#342 Nearest Shared Category in a Sorted Tree

easy

A shop's category ids are stored in a binary search tree with unique values. To show a "related products" banner for two products, you need the deepest category that has both of their category ids at or below it.

Write sharedCategory(root, p, q) that returns the value of the lowest common ancestor of the nodes with values p and q. A node counts as its own ancestor. Both values are always in the tree, and p may equal q.

Example 1

Input: root = [20,10,30,5,15,25,35], p = 5, q = 15
Output: 10

Both are smaller than 20, so go left. At 10, 5 goes left and 15 goes right: the paths split.

Example 2

Input: root = [20,10,30,5,15,25,35], p = 10, q = 15
Output: 10

15 is below 10, and 10 counts as its own ancestor.

Constraints

  • 1 <= number of nodes <= 10^5
  • All values are unique.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).