Skip to the code
cf.
+25 XP

#343 Shared Container of Two Panes

medium

In a split-pane layout tree (not sorted in any way), the user drags a divider between two panes. The divider belongs to the deepest container that holds both panes.

Write sharedContainer(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. Values are unique and both p and q are in the tree.

Example 1

Input: root = [1,2,3,4,5,6,7], p = 4, q = 5
Output: 2

4 and 5 are the two children of 2.

Example 2

Input: root = [1,2,3,4,5,6,7], p = 4, q = 7
Output: 1

4 is on the root's left side and 7 on its right side.

Constraints

  • 2 <= number of nodes <= 10^5
  • All values are unique.
  • p !== q

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).