zoukankan      html  css  js  c++  java
  • 【Binary Search Tree Iterator 】cpp

    题目:

    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. 

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

    代码:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    private:
        vector<TreeNode*> list;
        int index;
    public:
        BSTIterator(TreeNode *root) {
            BSTIterator::treeToList(root, this->list);
            this->index = 0;
        }
    
        static void treeToList(TreeNode* root, vector<TreeNode*>& ret)
        {
            if ( !root ) return;
            BSTIterator::treeToList(root->left, ret);
            ret.push_back(root);
            BSTIterator::treeToList(root->right, ret);
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return index < this->list.size();
        }
    
        /** @return the next smallest number */
        int next() {
            return list[index++]->val;
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */

    tips:

    这个题目的核心就是在于中序遍历 把BST转化成vector,这样可以实现题目的要求。

  • 相关阅读:
    错误 2 error C2059: 语法错误:“::”
    完全卸载session 所需要的函数
    header("Location:http://www.baidu.com");
    php str_pad() 用法
    php str_pad();
    设计模式系列-01-开篇
    博客园样式的设置系列-01-侧边栏和皮肤的设置
    vs20132015UML系列之-类图
    php获取当前时间和转换格式
    saltstack:multi-master configuration
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4646397.html
Copyright © 2011-2022 走看看