首页 > 其他 > 详细

Leetcode:230. 二叉搜索树中第K小的元素

时间:2020-03-03 14:17:19      阅读:66      评论:0      收藏:0      [点我收藏+]

Leetcode:230. 二叉搜索树中第K小的元素

Leetcode:230. 二叉搜索树中第K小的元素

思路:

利用BST的中序历遍的结果为其排序后的结果,我们可以利用其特性直接找到第k个中序遍历元素,即为问题答案。

Talk is cheap . Show me the code .

/**
 * 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:
    int cnt=0,ans=0;
    int kthSmallest(TreeNode* root, int k) {
        if(root==NULL) return ans;
        if(cnt==k) return ans;
        ans=kthSmallest(root->left,k);
        cnt++;
        if(cnt==k) ans=root->val;
        ans=kthSmallest(root->right,k);
        return ans;
    }
};

Leetcode:230. 二叉搜索树中第K小的元素

原文:https://www.cnblogs.com/cell-coder/p/12401911.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!