Here is the interview question prompt, presented for reference.
In the official React documentation, it's recommended that to find out where state
data should live, the following steps be taken:
This is an algorithmic problem-- let's find the lowest common ancestor!
You're given a binary search tree tree1
and two of its child nodes as parameters. Can you write a method lowestCommonAncestor(root: Node, node1: Node, node2: Node)
to identify the lowest common ancestor of the two nodes? The lowest common ancestor is the deepest node that has both of the two nodes as descendants.
In the below example, the lowest common ancestor of node 5
and 8
is 7
.
/*
7
/ \
4 8
/ \
1 5
*/
The method will called in the following manner: lowestCommonAncestor(root, node1, node2);
.
You can assume our standard node definition for the tree vertices:
// Node definition
function Node(val) {
this.val = val;
this.left = this.right = null;
}
# Node definition
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
Bonus: is there a way to find the lowest common ancestor of two nodes if the root wasn't passed as a parameter?
1000
-1000000000
and 1000000000
O(n)
O(1)
You can see the full challenge with visuals at this link.
Challenges • Asked about 5 years ago by Anonymous
This is the main discussion thread generated for Lowest Common Ancestor.
[deleted]