File tree Expand file tree Collapse file tree
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """
2+ 235. Lowest Common Ancestor of a Binary Search Tree
3+ https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
4+
5+ Solution:
6+ BST의 특성을 활용한다.
7+ 1) p, q 모두 현재 노드보다 작으면 → LCA는 왼쪽 서브트리에 존재
8+ 2) p, q 모두 현재 노드보다 크면 → LCA는 오른쪽 서브트리에 존재
9+ 3) 그 외의 경우 → 현재 노드가 LCA (p, q가 갈라지는 지점)
10+
11+ Time: O(log n) - 균형 BST 기준, 최악의 경우 O(n)
12+ Space: O(1)
13+ """
14+
15+
16+ # Definition for a binary tree node.
17+ class TreeNode :
18+ def __init__ (self , x ):
19+ self .val = x
20+ self .left = None
21+ self .right = None
22+
23+
24+ class Solution :
25+ def lowestCommonAncestor (
26+ self , root : "TreeNode" , p : "TreeNode" , q : "TreeNode"
27+ ) -> "TreeNode" :
28+ cur = root
29+ while cur :
30+ if p .val < cur .val and q .val < cur .val :
31+ cur = cur .left
32+ elif p .val > cur .val and q .val > cur .val :
33+ cur = cur .right
34+ else :
35+ return cur
You can’t perform that action at this time.
0 commit comments