/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
stack<TreeNode*> s;
public:
BSTIterator(TreeNode* root) {
find_left(root);
}
/** @return the next smallest number */
int next() {
TreeNode* tmp = s.top();
s.pop();
if(tmp->right!=nullptr) //如果有右子树,下一个点应该是右子树最左边的点,如果无右子树下一个点应该是其父节点,即栈顶元素
find_left(tmp->right);
return tmp->val;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(s.empty())
return false;
return true;
}
void find_left(TreeNode* root) //找当前节点最左边的结点并一路压栈
{
while (root!=nullptr)
{
s.push(root);
root = root->left;
}
}
};
中序遍历二叉搜索树得到排序的序列
对一个结点来说,将左边的入栈,弹栈,如果有右子树对右子树重复上述步骤,如果没有右子树继续弹栈。
转自:
https://leetcode.com/problems/binary-search-tree-iterator/discuss/52519/My-Solution-in-C%2B%2B-in-average-O(1)-time-and-uses-O(h)-memory
leetcode173 二叉搜索树迭代器
最新推荐文章于 2022-12-21 18:08:29 发布