您的位置:首页 > 理论基础 > 数据结构算法

【二叉树】BST第K小值【230. Kth Smallest Element in a BST】

2017-07-15 12:02 225 查看
题目链接:https://leetcode.com/problems/kth-smallest-element-in-a-bst/#/discuss

/**
* 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) {
return getOrder(root,k);
}
//  中序遍历
int getOrder(TreeNode* root,int& k){
if(root){
int t=getOrder(root->left,k);
if(!k) return t;
k--;
if(k) t=getOrder(root->right,k);
else t=root->val;
return t;
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息