leetcode 173. Binary Search Tree Iterator

来源:互联网 发布:我有域名如何使用 编辑:程序博客网 时间:2024/06/07 01:02

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.



class BSTIterator {vector<int>re;int k;public:BSTIterator(TreeNode *root) {if (root == NULL)return ;vector<TreeNode*>que;que.push_back(root);bool f = true;while (!que.empty()){if (f&&que.back()->left != NULL)que.push_back(que.back()->left);else{re.push_back(que.back()->val);TreeNode*n = que.back(); que.pop_back();if (n->right != NULL){que.push_back(n->right);f = true;}elsef = false;}}k = 0;}/** @return whether we have a next smallest number */bool hasNext() {return re.size() > k;}/** @return the next smallest number */int next() {return re[k++];}};

accepted


0 0
原创粉丝点击