zoukankan      html  css  js  c++  java
  • [LeetCode] Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

    Note:
    You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

    Follow up:
    What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

    分析:二叉搜索树中序遍历递增有序。

    相关题目:《剑指offer》63

    递归版本:

    /**
     * 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 kthSmallest(TreeNode* root, int k) {
            TreeNode* p = kthSmallest(root, &k);
            return p->val;
        }
        
        TreeNode* kthSmallest(TreeNode* root, int* k) {
            TreeNode* p = NULL;
            
            if (root->left != NULL) {
                p = kthSmallest(root->left, k);
            }
            
            if (p == NULL) {
                if (*k == 1)
                    p = root;
                (*k)--;
            }
            
            if (p == NULL && root->right != NULL)
                p = kthSmallest(root->right, k);
                
            return p;
        }
    };

    迭代版本:

    /**
     * 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 kthSmallest(TreeNode* root, int k) {
            TreeNode* p = root;
            
            stack<TreeNode*> s;
            int i = 0;
            while (p != NULL || !s.empty()) {
                if (p != NULL) {
                    s.push(p);
                    p = p->left;
                } else {
                    p = s.top();
                    s.pop();
                    i++;
                    if (i == k)
                        return p->val;
                    p = p->right;
                }
            }
        }
    };

     

  • 相关阅读:
    Idea debug报错Command line is too long
    云计算与虚拟化入门通识
    yield from语法
    python中 os._exit() 和 sys.exit(), exit(0)和exit(1) 的用法和区别
    python模块中sys.argv[]使用
    SQLAlchemy中Model.query和session.query(Model)的区别
    MAN VGEXTEND
    Python---基础---dict和set
    Python---基础---元组
    Python---基础---list(列表)
  • 原文地址:https://www.cnblogs.com/vincently/p/4778753.html
Copyright © 2011-2022 走看看