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

【Binary Search Tree Iterator 】cpp

时间:2015-07-14 20:26:17      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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,这样可以实现题目的要求。

【Binary Search Tree Iterator 】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4646397.html

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