Binary Search Tree Iterator解題報(bào)告

Description:

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.

題意:

給一個二叉搜索樹的根節(jié)點(diǎn),實(shí)現(xiàn)從小到大的迭代,每次調(diào)用函數(shù)next()都輸出當(dāng)前最小的節(jié)點(diǎn)的值,hasNext()則用于檢測是否還有剩下沒輸出的節(jié)點(diǎn)。

Link:

https://leetcode.com/problems/binary-search-tree-iterator/description/

解題方法:

對于二叉搜索樹,中序遍歷是最直接的方法,但是這道題要求O(h) space,也就是說差不多每層只能儲存1個節(jié)點(diǎn)。
所以在棧里面,從根節(jié)點(diǎn)開始,只壓棧本身和左孩子。
當(dāng)每次調(diào)用next()的時候,彈出一個結(jié)點(diǎn),如果這個節(jié)點(diǎn)有右孩子,則把右孩子當(dāng)成root再進(jìn)行一次構(gòu)造函數(shù)。

Time Complexity:

構(gòu)造函數(shù)O(h) time O(h) space
hasNext() O(1) time
next() O(1) time

完整代碼:

class BSTIterator 
{
public:
    BSTIterator(TreeNode *root) 
    {
        while(root)
        {
            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* curr = S.top();
        S.pop();
        if(curr->right)
        {
            TreeNode* rightChild = curr->right; 
            while(rightChild)
            {
                S.push(rightChild);
                rightChild = rightChild->left;
            }
        }
        return curr->val;
    }
private:
    stack<TreeNode*> S;
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容