File tree Expand file tree Collapse file tree 3 files changed +90
-0
lines changed
kth-smallest-element-in-a-bst
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 3 files changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Solution:
3
+ 1) preOrder Traversal
4
+ 2) k 번쨰 요소 return
5
+
6
+ Time: O(n)
7
+ Space: O(n)
8
+
9
+ """
10
+
11
+
12
+ class Solution :
13
+ def kthSmallest (self , root : Optional [TreeNode ], k : int ) -> int :
14
+ arr = []
15
+
16
+ def dfs (node ):
17
+ if not node :
18
+ return
19
+
20
+ dfs (node .left )
21
+ arr .append (node .val )
22
+ dfs (node .right )
23
+
24
+ dfs (root )
25
+
26
+ return arr [k - 1 ]
Original file line number Diff line number Diff line change
1
+ """
2
+ Solution:
3
+ BST 의 특징을 이용해 풀이할 예정이다.
4
+ 1) cur.val 보다 p.val, q.val 이 작으면 왼쪽 트리에 LCA 가 있다.
5
+ 2) cur.val 보다 p.val, q.val 이 크면 오른쪽 트리에 LCA 가 있다.
6
+ 3) 나머지 케이스는 본인이 LCA 이다.
7
+
8
+ Time: O(log(n))
9
+ Space: O(1)
10
+
11
+ """
12
+
13
+
14
+ class Solution :
15
+ def lowestCommonAncestor (
16
+ self , root : "TreeNode" , p : "TreeNode" , q : "TreeNode"
17
+ ) -> "TreeNode" :
18
+
19
+ cur = root
20
+ while cur :
21
+ if p .val < cur .val and q .val < cur .val :
22
+ cur = cur .left
23
+ elif cur .val < p .val and cur .val < q .val :
24
+ cur = cur .right
25
+ else :
26
+ return cur
27
+
28
+
29
+ """
30
+ Solution: 재귀
31
+ Time: O(log(n))
32
+ Space: O(log(n))
33
+ """
34
+
35
+
36
+ class Solution :
37
+ def lowestCommonAncestor (
38
+ self , root : "TreeNode" , p : "TreeNode" , q : "TreeNode"
39
+ ) -> "TreeNode" :
40
+
41
+ if p .val < root .val and q .val < root .val :
42
+ return self .lowestCommonAncestor (root .left , p , q )
43
+ elif p .val > root .val and q .val > root .val :
44
+ return self .lowestCommonAncestor (root .right , p , q )
45
+ else :
46
+ return root
Original file line number Diff line number Diff line change
1
+ """
2
+ Solution:
3
+ 1) 정렬
4
+ 2) prev endTime 이 cur startTime 보다 큰 경우가 있으면 return False
5
+ Time: O(n)
6
+ Space: O(1)
7
+ """
8
+
9
+
10
+ class Solution :
11
+ def canAttendMeetings (self , intervals : List [List [int ]]) -> bool :
12
+ intervals .sort ()
13
+
14
+ for i in range (1 , len (intervals )):
15
+ if intervals [i - 1 ][1 ] > intervals [i ][0 ]:
16
+ return False
17
+
18
+ return True
You can’t perform that action at this time.
0 commit comments