Home LeetCode - 230. Kth Smallest Element in a BST
Post
Cancel

LeetCode - 230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BST - medium

문제

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

제한사항

  • You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

입출력 예

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Example 1:
Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3

풀이

  • BFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        set<int> s;
        queue<TreeNode*> q;
        q.push(root);
        
        // BFS로 전체 노드의 val 값을 저장
        while(!q.empty()){
            auto node = q.front();
            q.pop();
            
            s.insert(node->val);
            
            if(node->left)
                q.push(node->left);
            
            if(node->right)
                q.push(node->right);
        }
        
        // k번째 작은수 검색
        auto answer = s.begin();
        for(auto i = 0 ; i < k - 1 ; ++i){
            ++answer;
        }
        
        return *answer;
    }
};
This post is licensed under CC BY 4.0 by the author.