力扣 173.二叉搜索树迭代器
作者:互联网
题面
题解(二叉树的非递归中序遍历)
将整棵树的最左边的一条链压入栈中,每次取出栈顶元素,并记录,如果它有右子树,那么将右子树最左边压入压栈中
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator {
public:
stack<TreeNode*> stk;
BSTIterator(TreeNode* root) {
while(root){
stk.push(root);
root=root->left;
}
}
int next() {
auto root =stk.top();
stk.pop();
int val = root -> val;
root = root -> right;
while(root){
stk.push(root);
root = root -> left;
}
return val;
}
bool hasNext() {
return stk.size();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
标签:right,TreeNode,val,int,173,二叉,力扣,root,left 来源: https://blog.csdn.net/qq_44791484/article/details/115791279