Kth Smallest Element in a BST

 

 遍历节点存入vector,之后排序,再取出相应的节点数据就可以了。

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) 
    {
        vector<int>l;
        preorderTraversal(root, l);
        sort(l.begin(),l.end());
        return l[k-1];
    }
    void preorderTraversal(TreeNode* root, vector<int> &l) 
    {
        if (root != NULL) {
            l.push_back(root->val);
            preorderTraversal(root->left, l);
            preorderTraversal(root->right, l);
        }
    }
};

  

posted @ 2021-04-23 18:58  章大佬  阅读(35)  评论(0)    收藏  举报