xinyu04

导航

LeetCode 230 Kth Smallest Element in a BST InOrder DFS中序遍历

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Solution

注意的一点是,中序遍历后,得到的是递增的序列,此时直接 \(O(1)\) 求解即可

点击查看代码
/**
 * 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;
    
    void inorder(TreeNode* root){
        if(!root)return;
        inorder(root->left);
        v.push_back(root->val);
        inorder(root->right);
    }
public:
    int kthSmallest(TreeNode* root, int k) {
        if(!root)return -1;
        inorder(root);
        return v[k-1];
    }
};

posted on 2022-05-26 15:19  Blackzxy  阅读(13)  评论(0编辑  收藏  举报