173. Binary Search Tree Iterator

題目

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()方法返回當前最小的元素,用hasNext()判斷是否還有元素,利用一個棧s保存從根節點到最左的所有元素,根據棧s的空與否判斷hasNext(),每次調用next()返回棧s的棧頂元素的值,同時對該元素從右孩子開始到最左側的進行壓棧,因爲這些是下一次需要的元素。

/**
 * 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() {
        return !s.empty();//根據棧是否爲空進行判斷
    }

    /** @return the next smallest number */
    int next() {
        TreeNode* temp=s.top();//返回棧頂元素並彈棧
        s.pop();
        TreeNode* l=temp->right;//從棧頂的右孩子開始,到最左側的所有元素壓棧
        while(l!=NULL){
            s.push(l);
            l=l->left;
        }
        return temp->val;
    }
    stack<TreeNode*> s;
};

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


發佈了180 篇原創文章 · 獲贊 15 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章