Largest value shared by two BSTs
I was asked this
No reports yet. Sign in to say where you were asked it.
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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.


