Kth-Smallest-Element-in-a-BST

题目地址

LeetCode#230 Kth Smallest Element in a BST

题目描述

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

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

Follow up:
  What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

解题思路

  题目要求找到树种第K个最小的值,可以将树的节点值保存到容器数组中,然后排序就可以了。emm

解题代码【.CPP】

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
/**
* 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 {
void getValue(TreeNode* root , vector<int>& values){
if(!root) return;
values.push_back(root->val);
getValue(root->left , values);
getValue(root->right , values);
}

public:
int kthSmallest(TreeNode* root, int k) {
vector<int> valuse(0);
getValue(root , valuse);
sort(valuse.begin(),valuse.end());
return valuse[k-1];
}
};
0%