您的位置:首页 > 其它

Leetcode : Binary Search Tree Iterator

2015-04-13 21:53 127 查看
题目描述

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) {
TreeNode *p = root;
while(p)//左节点不断入栈,相当于寻找中序遍历的第一个元素
{
temp.push(p);
p = p->left;
}

}

/** @return whether we have a next smallest number */
bool hasNext() {
return !temp.empty();
}

/** @return the next smallest number */
int next() {
TreeNode *q = temp.top();
int x = q->val;
temp.pop();
q=q->right;
while(q)//继续把右节点的左侧遍历入栈
{
temp.push(q);
q = q->left;
}
return x;

}
private:
stack<TreeNode *> temp;
};

/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: