[关闭]
@snuffles 2019-04-04T15:15:11.000000Z 字数 1051 阅读 919

L230 二叉搜索树中第K小的元素

查找


给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

解:二叉搜索树中序遍历得到从小到大的排序数组。

  1. //分治解法,统计左子树节点个数,用K判断在哪个子树里
  2. int kthSmallest(TreeNode* root, int k){
  3. int cnt = count(root->left);
  4. if(k<=cnt){
  5. return kthSmallest(root->left, k);
  6. }
  7. else if(k>cnt+1){
  8. return kthSmallest(root->right, k-cnt-1);
  9. }
  10. return root->val;
  11. }
  12. int count(TreeNode* root){
  13. if(!root) return 0;
  14. return 1+count(root->left)+count(root->right);
  15. }
////非递归解法,注意条件为CNT==K,STACK,P
int kthSmallest(TreeNode* root, int k){
    int cnt=0;
    stack<TreeNode*> s;
    TreeNode *p=root;
    // 左 中 右
    while(p || !s.empty()){
        while(p){
            s.push(p);
            p = p->left;
        }
        p = s.top(); s.pop();
        ++cnt;
        if(cnt == k) return p->val;
        p = p->right;
    }
    return 0;
}

////递归解法

  1. vector<int> num;
  2. int kthSmallest(TreeNode* root, int k) {
  3. posOrd(root);
  4. return num[k-1];
  5. }
  6. void posOrd(TreeNode* root){
  7. if(root == NULL) return;
  8. posOrd(root->left);
  9. num.push_back(root->val);
  10. posOrd(root->right);
  11. }

原本解法

  1. class Solution {
  2. public:
  3. vector<int> num;
  4. int kthSmallest(TreeNode* root, int k) {
  5. posOrd(root);
  6. return num[k-1];
  7. }
  8. void posOrd(TreeNode* root){
  9. if(root == NULL) return;
  10. posOrd(root->left);
  11. num.push_back(root->val);
  12. posOrd(root->right);
  13. }
  14. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注