天天看點

【leetcode 二叉樹 BST C++】230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BST

【leetcode 二叉樹 BST C++】230. Kth Smallest Element in a BST
/**
 * 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 {
public:
    int cnt = 0, result = 0;
    void inOrder(TreeNode* root, int k) {
        if(!root) return ;
        inOrder(root->left, k);
        cnt++;
        if(cnt == k) {
            result = root->val;
            return ;
        }
        inOrder(root->right, k);
    }
    int kthSmallest(TreeNode* root, int k) {
        inOrder(root, k);
        return result;
    }
};