173. Binary Search Tree Iterator

来源:互联网 发布:java io流写入文件 编辑:程序博客网 时间:2024/06/16 20:15

/** * 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)       {           stk.push(root);           root = root->left;       }    }    /** @return whether we have a next smallest number */    bool hasNext() {       return !stk.empty();    }    /** @return the next smallest number */    int next() {        TreeNode* tmp = stk.top();        int val = tmp->val;        stk.pop();        tmp = tmp->right;        while(tmp)        {            stk.push(tmp);            tmp = tmp->left;        }        return val;            }private:   stack<TreeNode*> stk;};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */

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.

【思路】暴力的方法是遍历整个树然后将所有元素放入有序的队列中,依次取出,但空间复杂度为O(n)。O(h)的复杂度的解法可通过一个栈来实现:依次将最左边的元素压栈,每次弹出最左下的元素即为最小的元素,同时判断其是否有右子树,若有右子树则继续将其右结点的左边元素依次压栈,循环直到栈为空。


0 0
原创粉丝点击