Leecode brush title
- Title Description
Given a binary search tree, write a function kthSmallest to find where the k-th smallest element.
Note:
You can assume that k is always active, 1 ≤ k ≤ number of binary search tree elements.
- Examples of a
- Example Two
- Code
/**
* 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:
//利用中序遍历即可得到从小到大的排列
void order_travel(TreeNode* t, int& c, int& val, int k)
{
if(t==NULL)
return;
else
{
order_travel(t->left, c, val, k);
c++;
if(c==k)
{
val = t->val;
return;
}
order_travel(t->right,c,val,k);
}
}
int kthSmallest(TreeNode* root, int k)
{
int val; //表示最终值
int c=0; //表示次数
order_travel(root, c, val, k);
return val;
}
};