Skip to content

Commit 81186eb

Browse files
committed
solve(w13): 235. Lowest Common Ancestor of a Binary Search Tree
1 parent ad3e83a commit 81186eb

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
2+
3+
# Definition for a binary tree node.
4+
# class TreeNode:
5+
# def __init__(self, x):
6+
# self.val = x
7+
# self.left = None
8+
# self.right = None
9+
10+
class Solution:
11+
def lowestCommonAncestor_recur(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
12+
"""
13+
[Complexity]
14+
- TC: O(height)
15+
- SC: O(height) (call stack)
16+
17+
[Approach]
18+
어떤 node와 두 노드 p, q 간의 관계를 다음의 케이스로 나누어 볼 수 있다.
19+
1) p와 q가 모두 현재 node 보다 작다면 --> left subtree로 내려가 살펴보기
20+
2) p와 q가 모두 현재 node 보다 크다면 --> right subtree로 내려가 살펴보기
21+
3) p와 q가 현재 node의 두 child subtree에 각각 존재한다면 --> 현재 node가 p, q의 LCA
22+
"""
23+
24+
def find_lca(node):
25+
# 1) p와 q가 모두 현재 node 보다 작다면 --> left subtree로 내려가 살펴보기
26+
if p.val < node.val > q.val:
27+
return find_lca(node.left)
28+
# 2) p와 q가 모두 현재 node 보다 크다면 --> right subtree로 내려가 살펴보기
29+
if p.val > node.val < q.val:
30+
return find_lca(node.right)
31+
# 3) p와 q가 현재 node의 두 child subtree에 각각 존재한다면 --> 현재 node가 p, q의 LCA
32+
return node
33+
34+
return find_lca(root)
35+
36+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
37+
"""
38+
[Complexity]
39+
- TC: O(height)
40+
- SC: O(1)
41+
42+
[Approach]
43+
이전 recursive 풀이를 iterative 하게 풀이할 수 있다.
44+
"""
45+
while root:
46+
# 1) p와 q가 모두 현재 node 보다 작다면 --> left subtree로 내려가 살펴보기
47+
if p.val < root.val > q.val:
48+
root = root.left
49+
# 2) p와 q가 모두 현재 node 보다 크다면 --> right subtree로 내려가 살펴보기
50+
elif p.val > root.val < q.val:
51+
root = root.right
52+
# 3) p와 q가 현재 node의 두 child subtree에 각각 존재한다면 --> 현재 node가 p, q의 LCA
53+
else:
54+
return root

0 commit comments

Comments
 (0)