您的位置:首页 > 编程语言 > C语言/C++

Kth Smallest Element in a BST

2016-06-05 10:17 543 查看
题目描述:

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.
解题思路:
考虑二叉搜索树的性质:中序遍历是递增有序的,因此可以中序遍历该二叉搜索树,找到第K个节点即可

AC代码如下:

class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
if (root == NULL) return 0;
int ans;
inorder(root, k, ans);
return ans;
}
void inorder(TreeNode* root, int& k,int& num){
if (k == 0) return;
if (root->left != NULL){
inorder(root->left, k,num);
}
k--;
if (0== k) num=root->val;
if (root->right != NULL){
inorder(root->right, k,num);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息