leetcode 173. Binary Search Tree Iterator

来源:互联网 发布:C语言aver 编辑:程序博客网 时间:2024/06/17 15:44

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.

思路其实和中序遍历一样,先把左子树压入,然后把遍历的时候再压入右子树。


/** * 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)     {        this->root = root;         push_stack(this->root);    }        void push_stack(TreeNode *node)    {        while(node)        {            m1.push(node);            node = node->left;        }    }        bool hasNext()     {        return (root && !m1.empty()) ? 1 : 0;    }    int next()     {        TreeNode *p = m1.top();        m1.pop();        push_stack(p->right); //p->right 是比 p 大一些的值        return p->val;    }   private:    TreeNode *root;    stack<TreeNode *> m1;   };/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */


原创粉丝点击