Nearest Common Ancestor

Start Timer

0:00:00

Upvote
3
Downvote
Save question
Mark as completed
View comments (3)

You are given a binary tree of unique positive numbers. Each node in the tree is implemented as a dictionary with the keys left and right, indicating the node’s left and right neighbors, respectively, and data that holds an integer value.

Given two nodes as input (value1 and value2), write a function to return the value of the nearest node that is a parent to both nodes.

Note: If one of the nodes doesn’t exist in the tree, return -1.

Example:

Input:

# Diagram of the binary tree
'''
      6        
     / \        
    3   9     
   / \
  2   11
     / \
    5   8
'''
value1 = 8
value2 = 2

Output:

common_ancestor(root,value1,value2) -> 3

As the parents for the nodes 8 and 2 are the root node 6 and the node 3. 3 is the nearest parent that has the two nodes as children.

.
.
.
.
.


Comments

Loading comments