zoukankan      html  css  js  c++  java
  • 902. Kth Smallest Element in a BST

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

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

    样例
    Given root = {1,2}, k = 2, return 2.

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    
    class Solution {
    public:
        /**
         * @param root: the given BST
         * @param k: the given k
         * @return: the kth smallest element in BST
         */
    
        //迭代遍历到最后(思考如何提前终止)
        int count = 0;
        int res;
        int kthSmallest(TreeNode * root, int k) {
            // write your code here
            if (root->left != NULL) kthSmallest(root->left, k);
            if (++count == k) res = root->val;     //①
            if (root->right != NULL) kthSmallest(root->right, k);
            return res;
        }
    
    
        
        //循环
        int kthSmallest(TreeNode * root, int k) {
            // write your code here
            std::stack<TreeNode*> sta;
            while (true) {
                while (root) {
                    sta.push(root);
                    root = root->left;
                }
                if (sta.empty()) break;
                root = sta.top();
                sta.pop();
                if(--k==0) return root->val;
                root = root->right;
            }
        }
    };
    
  • 相关阅读:
    C++003类的析构函数
    C++002类的构造函数
    C++001类
    simulink与控制系统仿真01自动控制原理简介
    telnet
    WEB
    Python_包
    Python_装饰器
    Pycharm+Tensorflow安装和使用出现的问题集合
    HTML+CSS综合使用
  • 原文地址:https://www.cnblogs.com/narjaja/p/10004277.html
Copyright © 2011-2022 走看看