Kth Smallest Element in a BST (the Kth smallest element in a C++ binary search tree)

Problem-solving ideas:

(1) In-order traversal, save the array

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    vector<int> v;
public:
    void helper(TreeNode *root) {
        if(!root) return;
        helper(root->left);
        v.push_back(root->val);
        helper(root->right);
    }

    int kthSmallest(TreeNode* root, int k) {
        helper(root);
        return v[k-1];
    }
};

 

Guess you like

Origin blog.csdn.net/coolsunxu/article/details/114915650