算法1
思路:非递归中序遍历,每次把根节点的左链放入栈中,如果左子树遍历完,将右子树的左链放到栈里
C++ 代码
/**
* 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();
*/