[leetcode] 173. Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.


这道题是实现BST迭代器,题目难度为Medium。


BST相信大家都熟悉,就不详细介绍了。根据BST的特点,中序遍历BST即得到节点值从小到大排列的所有节点。next()函数找下一个最小值节点,即中序遍历的下一节点,从根节点开始,一直向左子树遍历,直到遍历到左子树为空的节点为止,此时的节点即是初始的最小值节点遍历此节点,之后跳转到它的右子树(如果不为空)继续遍历,在遍历完右子树之后,以此节点为根的子树就遍历完了,此时要跳转到它的父节点继续遍历,所以这里需要借助栈来存储遍历路径上的所有节点以便回退时使用,即中序遍历二叉树的思路。


题目限定时间复杂度O(1),空间复杂度O(h),所以构造函数要将栈中数据预先准备好,以便next()函数返回栈顶元素;hasNext()函数判断栈是否为空即可;next()函数在出栈返回最小值之后,要跳转到最小值节点的右子树继续中序遍历的相应操作。具体代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
    stack<TreeNode*> stk;
public:
    BSTIterator(TreeNode *root) {
        while(root) {
            stk.push(root);
            root = root->left;
        }
    }

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

    /** @return the next smallest number */
    int next() {
        TreeNode* n = stk.top();
        int ret = n->val;
        stk.pop();
        n = n->right;
        while(n) {
            stk.push(n);
            n = n->left;
        }
        return ret;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */
空间复杂度O(h)达到了,hasNext()函数的时间复杂度O(1)也达到了,next()函数至多调用节点个数次,而栈的入栈和出栈最多也是节点个数次,所以next()函数的平均时间复杂度也是O(1)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值