您的位置:首页 > 其它

binary-search-tree-iterator

2016-02-29 21:24 183 查看
https://leetcode.com/problems/binary-search-tree-iterator/

利用非递归 中序遍历的思想

class BSTIterator {
private:
stack<TreeNode*> s;
public:
BSTIterator(TreeNode *root) {
while (!s.empty())
s.pop();
while (root)
{
s.push(root);
root = root->left;
}
}

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

/** @return the next smallest number */
int next() {
TreeNode *temp;
int minvalue;
temp = s.top();
s.pop();
minvalue = temp->val;
temp = temp->right;
while (temp)
{
s.push(temp);
temp = temp->left;
}
return minvalue;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: