Skip to content

Commit 61ce91d

Browse files
committed
problem: 0230 kth smallest element in a BST
1 parent eeeb732 commit 61ce91d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# 0230. Kth Smallest Element in a BST
2+
3+
* Difficulty: medium
4+
* Link: https://leetcode.com/problems/kth-smallest-element-in-a-bst/
5+
* Topics: DFS-BFS
6+
7+
8+
# Clarification
9+
10+
1. Check the inputs and outputs
11+
12+
# Solution (DFS)
13+
14+
### Thought Process
15+
16+
- ****Recursive Inorder Traversal****
17+
18+
![Untitled](./Untitled.png)
19+
20+
- Implement
21+
22+
```python
23+
# Definition for a binary tree node.
24+
# class TreeNode:
25+
# def __init__(self, val=0, left=None, right=None):
26+
# self.val = val
27+
# self.left = left
28+
# self.right = right
29+
class Solution:
30+
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
31+
def inorder(root):
32+
if not root:
33+
return []
34+
return inorder(root.left) + [root.val] + inorder(root.right)
35+
36+
return inorder(root)[k-1]
37+
```
38+
39+
40+
### Complexity
41+
42+
- Time complexity: *O*(*N*) to build a traversal.
43+
- Space complexity: *O*(*N*) to keep an inorder traversal.
44+
45+
# Note
46+
47+
- BST 的中序遍歷結果是有序的(升冪)
Loading

0 commit comments

Comments
 (0)