Skip to content

Commit db392ff

Browse files
authoredDec 26, 2021
Create 236-Lowest-Common-Ancestor-of-a-Binary-Tree.py
1 parent f2da16a commit db392ff

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
res = None
10+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
11+
if not root or not p or not q: return None
12+
13+
def search(root, p, q):
14+
if not root: return False
15+
mid = left = right = False
16+
if root.val == p.val or root.val == q.val:
17+
mid = True
18+
19+
left = search(root.left, p, q)
20+
right = search(root.right, p, q)
21+
if mid:
22+
if left or right:
23+
self.res = root
24+
elif left and right:
25+
self.res = root
26+
return mid or left or right
27+
28+
search(root, p, q)
29+
return self.res

0 commit comments

Comments
 (0)
Please sign in to comment.