【leetcode】Binary Search Tree Iterator

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: vector<int> vals;
int index;
BSTIterator(TreeNode *root) {
DFS(root);
index=-;
} void DFS(TreeNode *root)
{ if(root==NULL) return; DFS(root->left);
vals.push_back(root->val);
DFS(root->right);
} /** @return whether we have a next smallest number */
bool hasNext() { if(index<(int)vals.size()-) return true;
else return false; } /** @return the next smallest number */
int next() {
return vals[++index];
}
}; /**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
 
 
运用二叉排序树的性质
 
首先连同root把所有左边节点都push到堆栈中,
然后每当调用next时,返回堆栈栈顶元素,然后把栈顶元素的右孩子,以及他的所有左子树都压入栈即可
 
 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public: stack<TreeNode*> stk;
BSTIterator(TreeNode *root) {
pushLeftNode(root); } void pushLeftNode(TreeNode *root)
{ while(root!=NULL)
{
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 * smallestNode=stk.top();
stk.pop();
pushLeftNode(smallestNode->right);
return smallestNode->val;
}
}; /**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
上一篇:用委托在listbox中异步显示信息,解决线程间操作无效,从不是创建控件的线程访问它


下一篇:Django rest framework 源码分析 (1)----认证