Skip to content

Commit 2d3ea50

Browse files
committed
create 0236-lowest-common-ancestor-of-a-binary-tree.py
1 parent 973981e commit 2d3ea50

File tree

1 file changed

+26
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)