File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Constraints:
3
+ - The number of nodes in the tree is in the range [2, 10^5].
4
+ - -10^9 <= Node.val <= 10^9
5
+ - All Node.val are unique.
6
+ - p != q
7
+ - p and q will exist in the BST.
8
+
9
+ Time Complexity: O(h)
10
+ - ์ฌ๊ธฐ์ h๋ ํธ๋ฆฌ์ ๋์ด
11
+
12
+ Space Complexity: O(1)
13
+ - node ๋ณ์๋ง ์ฌ์ฉํ๋ฏ๋ก ์์๊ณต๊ฐ
14
+
15
+ ํ์ด๋ฐฉ๋ฒ:
16
+ 1. LCA ๋
ธ๋๋:
17
+ - ๋ ๋
ธ๋ ์ค ํ๋๊ฐ ๋ค๋ฅธ ํ๋์ ์กฐ์์ธ ๊ฒฝ์ฐ, ์์์ ์์นํ ๋
ธ๋๊ฐ LDA
18
+ - ๊ทธ๋ ์ง ์์ผ๋ฉด, ๋ ๋
ธ๋๋ฅผ ํ๊ณ ์๋ก ์ฌ๋ผ๊ฐ๋ฉด ์ฒ์ ๋ง๋๋ ๋
ธ๋๊ฐ LDA
19
+ 2. BST์์ LCA ์ฐพ๊ธฐ:
20
+ - ํ์ฌ ๋
ธ๋์ ๊ฐ์ด p์ q๋ณด๋ค ํฐ ๊ฒฝ์ฐ -> ์ผ์ชฝ์ผ๋ก ์ด๋
21
+ - ํ์ฌ ๋
ธ๋์ ๊ฐ์ด p์ q๋ณด๋ค ์์ ๊ฒฝ์ฐ -> ์ค๋ฅธ์ชฝ์ผ๋ก ์ด๋
22
+ - ๊ทธ ์ธ์ ๊ฒฝ์ฐ(ํ์ฌ ๋
ธ๋๊ฐ p์ q ์ฌ์ด์ ์๊ฑฐ๋ p๋ q ์ค ํ๋์ ๊ฐ์ผ๋ฉด) -> ํ์ฌ ๋
ธ๋๊ฐ LCA
23
+ """
24
+ # Definition for a binary tree node.
25
+ # class TreeNode:
26
+ # def __init__(self, x):
27
+ # self.val = x
28
+ # self.left = None
29
+ # self.right = None
30
+
31
+ class Solution :
32
+ def lowestCommonAncestor (self , root : 'TreeNode' , p : 'TreeNode' , q : 'TreeNode' ) -> 'TreeNode' :
33
+ node = root
34
+
35
+ while node :
36
+
37
+ if p .val < node .val and q .val < node .val :
38
+ node = node .left
39
+
40
+ elif p .val > node .val and q .val > node .val :
41
+ node = node .right
42
+
43
+ else :
44
+ return node
You canโt perform that action at this time.
0 commit comments