InferenceAI

Enter at least two characters to search.

Start free

Search Tree Common Ancestor

mediumTrees25 min25 XP

Given a valid binary search tree and two values p and q that both exist in it, return the value of their lowest common ancestor: the deepest node that has both as descendants (a node counts as its own descendant).

Trees are given in level order as a list, with None for a missing child (for example [3, 9, 20, None, None, 15, 7]).

Requirements

  • Use the BST ordering to run in O(h)O(h) time, where hh is the tree height.

Examples

EXAMPLE WALKTHROUGHsplit at root

A guided view of the published example, not a trace of your code.

INPUT[[6,2,8,0,4,7,9,null,null,3,5],2,8]
TASKsearch_tree_common_ancestor()
EXPECTED OUTPUT6

Start with the input values shown in this example.

Example 1 of 3

Input: values = [6,2,8,0,4,7,9,null,null,3,5], arg2 = 2, arg3 = 8

Output: 6

Explanation: split at root

Input: values = [6,2,8,0,4,7,9,null,null,3,5], arg2 = 2, arg3 = 4

Output: 2

Explanation: ancestor is one of them

Input: values = [2,1], arg2 = 2, arg3 = 1

Output: 2

Explanation: two nodes

Hint 1

If both values are smaller than the current node, go left; if both are larger, go right; otherwise you are at the split point.

Topics

DSATreesPython