LeetCode---Binary Search Tree Iterator ---C++

問題描述:

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.

對BST,實現一個迭代器。

思路:對於BST,其中序遍歷爲排序的。中序遍歷的非遞歸方法,就用到了一個棧。所以該題的思路就是用一個棧來實現。因此BST的迭代器類,有一個私有的stack,在構造函數中把BST中最左邊的節點入棧。然後hasnext()函數返回true當棧中還有元素時。next,出棧,返回值爲該節點的val,然後判斷是否有右節點,若有,則把該節點及其所有左節點入棧。

/**
 * 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 != NULL )
        {
            S.push(root);
            root = root->left;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        if(S.size() > 0)
            return true;
        return false;
    }

    /** @return the next smallest number */
    int next() {
        int result = 0;
        if(!S.empty())
        {
            TreeNode* node = S.top();
            result = node->val;
            S.pop();
            node = node->right;
            while(node != NULL)
            {
                S.push(node);
                node = node->left;
            }
            
        }
        return result;
    }
    private:
    std::stack<TreeNode*> S;
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章