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.
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.
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.
1 <= number of nodes <= 10^5Trees 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.
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).
I'm here to help with #342 Nearest Shared Category in a Sorted Tree. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.