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

    该题的思路非常easy。就是对BST进行先序遍历,找到第k个数的时候返回。

    这里借助栈用迭代实现,递归的代码更简单,没有尝试。

    class Solution {
    public:
        int kthSmallest(TreeNode* root, int k) {
            stack<TreeNode *> cache;
            TreeNode *point = root;
            TreeNode *tmp;
            int i = 0;
    //先序遍历
            while(point || !cache.empty()){
                while(point){
                    cache.push(point);
                    point = point -> left;
                }
                if(!cache.empty()){
                    tmp = cache.top();
                    i++;
                    if(i == k)
                        return tmp -> val;
                    cache.pop();
                    point = tmp -> right;
                }
            }
        }
    };



  • 相关阅读:
    CSS定位属性
    CSS属性
    CSS基础
    HTML
    JDBC
    语言元素
    初识Python
    redis配置文件
    zabbix
    jumpserver
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6694104.html
Copyright © 2011-2022 走看看