标签:
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.
实现一个基于二叉搜索树的类iterator。初始化iterator为这棵树的根节点root.。调用next()函数返回这棵树的下一个最小的值。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { stack<TreeNode*> qu; public: BSTIterator(TreeNode *root) { push_in_stack(root); } /** @return whether we have a next smallest number */ bool hasNext() { return !qu.empty(); } /** @return the next smallest number */ int next() { TreeNode *tmpNode = qu.top(); qu.pop(); push_in_stack(tmpNode->right); return tmpNode->val; } private: void push_in_stack(TreeNode* node) { while(node) { qu.push(node); node=node->left; } } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
while (i.hasNext()) cout << i.next();
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/46793875