leetcode 230 Kth Smallest Element in a BST C++

来源:互联网 发布:天津中年同志软件 编辑:程序博客网 时间:2024/05/22 00:25

先用简单的方法,中序遍历放到一个数组里面,取k-1即可。

    vector<int> vec;    void inorder(TreeNode *root) {        if (!root) return;        inorder(root->left);        vec.push_back(root->val);        inorder(root->right);    }    int kthSmallest(TreeNode* root, int k) {        inorder(root);        return vec[k-1];    }

但是效率比较低。

后来用了这种,直接在递归的过程中找,因为每次遍历都相当于拿到了一个节点,并且是递增的。

    int val = 0;    int sum = 0;    int numK;    void inorder(TreeNode *root) {        if(!root) return;        inorder(root->left);        if(++sum == numK) {          val = root->val;          return;        }         inorder(root->right);    }    int kthSmallest(TreeNode* root, int k) {        numK = k;        inorder(root);        return val;    }


0 0
原创粉丝点击