diff --git a/src/my_project/interviews/amazon_high_frequency_23/round_7/lowest_common_ancestor_binary_tree_iv.py b/src/my_project/interviews/amazon_high_frequency_23/round_7/lowest_common_ancestor_binary_tree_iv.py new file mode 100644 index 00000000..c9117ad4 --- /dev/null +++ b/src/my_project/interviews/amazon_high_frequency_23/round_7/lowest_common_ancestor_binary_tree_iv.py @@ -0,0 +1,29 @@ +from typing import List, Union, Collection, Mapping, Optional + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution: + def lowestCommonAncestor(self, root: TreeNode, nodes: List[TreeNode]) -> 'TreeNode': + + node_set = set(nodes) + + def dfs(node: TreeNode): + + if not node or node in node_set: + return node + + left = dfs(node.left) + right = dfs(node.right) + + if left and right: + return node + + return left if left else right + + return dfs(root) + \ No newline at end of file