Your question is Binary Tree: Most Recent Common Ancestor. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
Clearwater Analytics can represent hierarchical investment data with ordered tree structures. Given a binary search tree and two existing node values, return the value of their most recent, or lowest, common ancestor.
Implement lowest_common_ancestor(root, p, q).
root is a non-empty nested dictionary with the shape { "val": int, "left": node | None, "right": node | None }.p and q are distinct integer values that exist in the tree.p and q. A node is considered its own ancestor.Use the BST ordering property rather than traversing every node. Your solution should work for a highly unbalanced tree.
def lowest_common_ancestor(root, p, q):