230. Kth Smallest Element in a BST(Tree)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyuanzong/article/details/85524434

链接:https://leetcode.com/problems/kth-smallest-element-in-a-bst/

题目:求BST第k小元素

思路:中序遍历,然后计数。

代码:

class Solution {
public:
    void order(TreeNode *root,int k){
        if(!root || num > k) return;
            
        order(root->left,k);
        
        if(num == k) ret = root->val;  //找到第k小元素
        num++;  //计数
        
        order(root->right,k);
    }
    
    int kthSmallest(TreeNode* root, int k) {
        num = 1;
        order(root,k);
        return ret;
    }
    
private:
    int ret;
    int num;
};

猜你喜欢

转载自blog.csdn.net/tangyuanzong/article/details/85524434