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;
                }
            }
        }
    };

     

  • 相关阅读:
    本地快速搭建 FTP 服务器
    css 四个角
    时间
    两个json深度对比
    工作常用
    js模块化 中的变量可在局部 中的‘全局共享’
    datatables 的导出button自定义
    css布局技巧
    datables自定义排序
    js判断是否为空 或者全部为空
  • 原文地址:https://www.cnblogs.com/vincently/p/4778753.html
Copyright © 2011-2022 走看看