zoukankan      html  css  js  c++  java
  • 【Kth Smallest Element in a BST 】cpp

    题目:

    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?

    Hint:

    1. Try to utilize the property of a BST.
    2. What if you could modify the BST node's structure?
    3. The optimal runtime complexity is O(height of BST).

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    代码:

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

    tips:

    直观的做法是中序遍历BST,然后获得第k个元素。

  • 相关阅读:
    透过书本了解HTML5
    Seam性能讨论
    Maven依赖管理
    Tapestry
    为HTML5的未来制定学习计划
    后缀数组
    HDU 1042(大数)
    教你理解复杂的C/C++声明
    编程修养
    平衡二叉树
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4645159.html
Copyright © 2011-2022 走看看