코딩테스트/BFS,DFS

[leetCode] 230. Kth Smallest Element in a BST

minkg3532 2026. 5. 29. 20:23

https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/

 

Kth Smallest Element in a BST - LeetCode

Can you solve this real interview question? Kth Smallest Element in a BST - Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.   Example 1: [https://assets.leetco

leetcode.com

 

k번째 작은 노드 수를 구하는 간단한 문제이다. 순서대로 노드를 벡터에 담고, sorting해 준다음 해당 인덱스를 지정해서 리턴해 주면 끝

 

더보기
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <algorithm>

class Solution {
private:
    int minCount;
public:
    int kthSmallest(TreeNode* root, int k) 
    {
        minCount = k;
        vector<int> v;
        Search(root, v);
        sort(v.begin(), v.end());

        return v[minCount - 1];
    }
    void Search(TreeNode* node, vector<int>& v)
    {
        if(node==nullptr)
            return;
        
        v.push_back(node->val);

        Search(node->left, v);
        Search(node->right, v);
    }

};