zoukankan      html  css  js  c++  java
  • Binary Search Tree Iterator -- leetcode

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

    Calling next() will return the next smallest number in the BST.

    Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.


    基本思路:

    事实上就是中序遍历的非递实现。


    这next smallest意思就是。从小到大逐个返回。 第一次看到,居然理解反了。还以为是从大到小逐个返回。


    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    public:
        BSTIterator(TreeNode *root) {
            while (root) {
                s_.push(root);
                root = root->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return !s_.empty();
        }
    
        /** @return the next smallest number */
        int next() {
            auto root = s_.top();
            s_.pop();
            auto ans = root->val;
            root = root->right;
            while (root) {
                s_.push(root);
                root = root->left;
            }
            return ans;
        }
    
    private:
        stack<TreeNode *> s_;
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */


  • 相关阅读:
    jdk1.8新特性
    linux centos虚拟机安装
    linux基本命令介绍
    JavaScript与Java的区别
    jQuery UI的基本使用方法与技巧
    jQuery Ajax 实例 ($.ajax、$.post、$.get)
    .NET批量大数据插入性能分析及比较
    .NET中的CSV导入导出(实例)
    jquery中push()的用法(数组添加元素)
    .net如何后台批量删除
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5265664.html
Copyright © 2011-2022 走看看