Skip to content

Commit 68d542c

Browse files
author
Jinbeom
committed
Lowest Common Ancestor of a Binary Search Tree Solution
1 parent 277e0b7 commit 68d542c

File tree

1 file changed

+20
-0
lines changed
  • lowest-common-ancestor-of-a-binary-search-tree

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution:
2+
# 시간복잡도: O(N)
3+
# 공간복잡도: O(1)
4+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
5+
def find(node):
6+
if not node:
7+
return None
8+
9+
left = find(node.left)
10+
right = find(node.right)
11+
12+
if node == p or node == q:
13+
return node
14+
15+
if left and right:
16+
return node
17+
18+
return left or right
19+
20+
return find(root)

0 commit comments

Comments
 (0)