-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlowestCommonAncestor1.py
More file actions
46 lines (35 loc) · 1.2 KB
/
lowestCommonAncestor1.py
File metadata and controls
46 lines (35 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return
x = self.lowestCommonAncestor(root.left,p,q)
y = self.lowestCommonAncestor(root.right,p,q)
if x and y:
return root
if root == p or root == q:
return root
if x or y:
return x or y
return None
# self.found1= False
# self.found2=False
# def dfs(node):
# if node==None:
# return
# print(node.val)
# if self.found1 and self.found2:
# return node
# else:
# if node==p:
# self.found1=True
# if node==q:
# self.found2=True
# dfs(node.left)
# dfs(node.right)
# return dfs(root)