lintcode86. 二叉查找樹迭代器

https://www.lintcode.com/problem/binary-search-tree-iterator/description

看着這個題無比眼熟

之前亞麻暑假實習manager問過我

然而 那會是有父指針的

這個題思路是什麼呢?

就變成了純正的中序遍歷

非遞歸版的

而且寫法也有要求

不能是while循環在外面的

是要while current的

然後就出了

class BSTIterator {
public:
    /*
    * @param root: The root of binary tree.
    */
    TreeNode* current;
    std::stack<TreeNode*> s ;
    BSTIterator(TreeNode * root) {
        // do intialization if necessary
        while (!s.empty()) s.pop();
        current = root;
    }

    /*
     * @return: True if there has next node, or false
     */
    bool hasNext() {
        // write your code here
        if (!s.empty() || current) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * @return: return next node
     */
    TreeNode * next() {
        // write your code here
        if(hasNext()) {
            while (current) {
                s.push(current);
                current = current ->left;
            }
            if (!s.empty()) {
                current = s.top();
                s.pop();
                TreeNode* c = current;
                current = current->right;
                return c;
            }
            
        } else return NULL;
    }
};

 

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