码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search Tree Iterator--LeetCode

时间:2015-04-14 13:01:30      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:c++   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.

思路:依靠栈数据结构,然后中序遍历的思想

class BSTIterator {
public:
    BSTIterator(BinTree *root) {
      while(!st.empty())
        sk.pop();
      BinTree* temp=root;
      while(temp != NULL)
      {
        sk.push(temp);
        temp = temp->left;
      }  
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return sk.empty();
    }

    /** @return the next smallest number */
    int next() {
        BinTree* res = sk.top();
        sk.pop();
        BinTree* temp = res->right;
        while(temp != NULL)
        {
          sk.push(temp);
          temp = temp->left;
        }
        return res->value;
    }
private:
        stack<BinTree*> sk;
};


Binary Search Tree Iterator--LeetCode

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/45039669

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!