[Binary search tree] leetcode173: binary search tree iterators (medium)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43152052/article/details/100177803

topic:
Here Insert Picture Description

Solution:
This problem is a predetermined time complexity O (h) instead of O (n), with a stack simulations we order traversal, the left node binary sort tree stored in the stack, the top element is the smallest value. Space complexity is O (1), the top element directly back on it.
Thinking:
only the nodes in preorder previous minimum value pushed onto the stack when taken out next we return to the top element is the minimum value, of course, required before the next minimum value is found, and all on the path node onto the stack for use, just to see if the head of iterations to determine whether the stack is empty can.

code show as below:

class BSTIterator {
private:
    stack<TreeNode*> record;
public:
    BSTIterator(TreeNode* root) {
       while(root){//中序遍历将左子树的所有左节点全部压入栈中,栈顶元素为最小值
           record.push(root);
           root=root->left;
       }
    }
    /** @return the next smallest number */
    int next() {
        TreeNode* node=record.top();record.pop();
        int result=node->val;//栈顶元素为最小值
        node=node->right;//下一个最小值当然出现在node节点的右子树中
        while(node)//在将最小值找到后,需要将下一个最小值找到
        {
            record.push(node);
            node=node->left;
        }
        return result;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {//判断栈是否为空即可
        return !record.empty();
    }
};

Guess you like

Origin blog.csdn.net/qq_43152052/article/details/100177803