InferenceAI

Enter at least two characters to search.

Start free

Lowest Common Ancestor

mediumTrees25 min25 XP

Given a binary tree with distinct values and two values p and q that both exist in it, return the value of their lowest common ancestor (a node counts as its own descendant). Unlike a BST, there's no ordering to use.

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

Examples

EXAMPLE WALKTHROUGHsplit at root

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

INPUT[[3,5,1,6,2,0,8,null,null,7,4],5,1]
TASKlowest_common_ancestor()
EXPECTED OUTPUT3

Start with the input values shown in this example.

Example 1 of 3

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

Output: 3

Explanation: split at root

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

Output: 5

Explanation: ancestor is one of them

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

Output: 1

Explanation: two nodes

Hint 1

Recurse into both children. If both sides find a target, the current node is the answer; otherwise pass up whichever side found one.

Topics

DSATreesPython