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);
}
};
'코딩테스트 > BFS,DFS' 카테고리의 다른 글
| [leetCode] 98. Validate Binary Search Tree (0) | 2026.05.29 |
|---|---|
| [leetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal (0) | 2026.05.29 |
| [leetCode] 572. Subtree of Another Tree (0) | 2026.05.29 |
| [leetCode] 297. Serialize and Deserialize Binary Tree (0) | 2026.05.29 |
| [leetCode] 79. Word Search (0) | 2026.05.29 |