题目描述
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.
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
题目思路
- 二叉树的中序遍历,然后每次计数,直到第 k 个节点
代码 C++
/**
* 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) {
int a = 0; // 因为引用,在此直接传入 0 是不行的
TreeNode* temp = core(root, k, a);
return temp->val;
}
// 注意此处必须为引用类型,因为len是计数的
// 如果不是引用类型则无法完成计数功能,毕竟递归
// 如果不用引用,上一层的len无法获取下一层len的数值变化
TreeNode* core(TreeNode* root, int k, int& len){
TreeNode* temp = NULL;
if(root != NULL){
temp = core(root->left, k, len);
if(temp != NULL){
return temp;
}
len = len + 1;
if(len == k){
return root;
}
temp = core(root->right, k ,len);
if(temp != NULL){
return temp;
}
}
return NULL;
}
};