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

     

  • 相关阅读:
    learning java identityHashCode
    learning java 获取环境变量及系统属性
    learning java 获取键盘输入
    learning svn add file execuable
    φ累积失败检测算法(转)
    层次锁(转)
    一致性算法中的节点下限(转)
    Fast Paxos(转)
    Zookeeper的一致性协议:Zab(转)
    FLP impossibility
  • 原文地址:https://www.cnblogs.com/vincently/p/4778753.html
Copyright © 2011-2022 走看看