← Questions

Largest value shared by two BSTs

0

You are given the roots of two binary search trees, a and b, holding integer values. Return the largest integer that appears in both trees. If the trees share no value, return -1.

Implement:

def largest_common_value(a: TreeNode | None, b: TreeNode | None) -> int: ...

where TreeNode has val, left and right.

Constraints

  • Each tree has between 1 and 10^5 nodes.
  • Every node value is between -10^9 and 10^9.
  • Both inputs are valid BSTs: every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger.
  • Trees may be unbalanced, so the height can be as large as the node count.

Aim for better than O(n) extra memory by using the BST ordering.

Example 1

Tree a values: 1, 3, 6, 8, 10, 12, 15
Tree b values: 2, 4, 6, 7, 10, 11, 14
Output: 10

Both 6 and 10 appear in both trees. 10 is the larger one.

Example 2

Tree a values: 2, 5, 9
Tree b values: 1, 4, 7
Output: -1

No value appears in both trees.

Reconstructed from the reported question; details may differ from what interviewers ask.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding