欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 230 Kth Smallest Element in a BST

程序员文章站 2022-06-05 16:43:20
...

题目链接:点击这里
LeetCode 230 Kth Smallest Element in a BST
LeetCode 230 Kth Smallest Element in a BST

/**
 * 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 inorder(TreeNode* r, vector<int>& v)
    {
        if(r!=NULL)
        {
            inorder(r->left, v);
            v.push_back(r->val);
            inorder(r->right, v);
        }
    }

    int kthSmallest(TreeNode* root, int k) {
        vector<int> v;
        inorder(root, v);
        return v[k-1];
    }
};