Kth Smallest Element in a BST @LeetCode
PROBLEM :
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.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* 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 min ;
KthSallestEle(root,&k,&min) ;
return min ;
}
void KthSallestEle(TreeNode *root,int *k,int *min){
if(root->left)
KthSallestEle(root->left,&(*k),&(*min)) ;
(*k)-- ;
if((*k)==0){
(*min)=root->val ;
return ;
}
if(root->right)
KthSallestEle(root->right,&(*k),&(*min)) ;
}
};
---------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* 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 min ;
KthSallestEle(root,&k,&min) ;
return min ;
}
void KthSallestEle(TreeNode *root,int *k,int *min){
if(root->left)
KthSallestEle(root->left,&(*k),&(*min)) ;
(*k)-- ;
if((*k)==0){
(*min)=root->val ;
return ;
}
if(root->right)
KthSallestEle(root->right,&(*k),&(*min)) ;
}
};
---------------------------------------------------------------------------------
Comments
Post a Comment