1
+ # Definition for a binary tree node.
2
+ # class TreeNode:
3
+ # def __init__(self, x):
4
+ # self.val = x
5
+ # self.left = None
6
+ # self.right = None
7
+
8
+ class Solution :
9
+ def lowestCommonAncestor (self , root : 'TreeNode' , nodes : 'List[TreeNode]' ) -> 'TreeNode' :
10
+ if not nodes :
11
+ return None
12
+ if len (nodes ) == 1 :
13
+ return nodes [0 ]
14
+
15
+ self .commonAncestors = set ()
16
+ targetNodes = set (x .val for x in nodes )
17
+ self .found = len (nodes )
18
+
19
+ def dfs (curr : 'TreeNode' , currentSet : 'Set[TreeNode]' , depth : int ) -> None :
20
+ if not curr or not self .found :
21
+ return
22
+ currentSet .add ((depth , curr ))
23
+
24
+ if curr .val in targetNodes :
25
+ self .found -= 1
26
+ if not self .commonAncestors :
27
+ for x in currentSet :
28
+ self .commonAncestors = currentSet .copy ()
29
+ self .commonAncestors &= currentSet
30
+
31
+ # even if something's below us, none of
32
+ # the inbetween nodes will matter
33
+ currentSet .remove ((depth , curr ))
34
+ return
35
+
36
+ dfs (curr .left , currentSet , depth + 1 )
37
+ dfs (curr .right , currentSet , depth + 1 )
38
+ currentSet .remove ((depth , curr ))
39
+
40
+ dfs (root , set (), 0 )
41
+
42
+ depth , node = self .commonAncestors .pop ()
43
+ while self .commonAncestors :
44
+ tempDepth , tempNode = self .commonAncestors .pop ()
45
+ if tempDepth > depth :
46
+ depth , node = tempDepth , tempNode
47
+
48
+ return node
0 commit comments