173. Binary Search Tree Iterator

题目:Binary Search Tree Iterator

原题链接:https://leetcode.com/problems/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.

设计一个二叉查找树的迭代器,迭代器的初始化用一个二叉查找树的根节点来进行。
next()函数用来返回二叉查找树中下一个最小的数值。
注意:next()和hasNext()的时间复杂度和空间复杂度应该分别限制在O( 1 )和O( h ),h是指这个二叉树的高度。

简单来说就是,按照从小到大的顺序返回二叉查找树的数值。
我们知道,对二叉查找树进行中序遍历可以得到二叉查找树的从小到大的排序序列。
所以,我们可以在初始化阶段就把这个排序序列给存起来,然后设置一个index来记录当前已经输出的元素在数组里面的下标,然后每次迭代输出时当前下标对应的元素,并让下标自加1,这个方法在next()和hasNext()函数里面无论是时间复杂度还是空间复杂度都能做到O(1),算是超额完成了题目的任务。

代码如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
private:
    vector<int> ans;
    int index, len;
public:
    void inOrder(TreeNode* root) {
        if(root == NULL) return;
        inOrder(root->left);
        ans.push_back(root->val);
        inOrder(root->right);
    }
    BSTIterator(TreeNode *root) {
        inOrder(root);
        len = ans.size();
        if(!len) index = -1;
        else index = 0;
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        if(index == -1) return false;
        if(index <= len - 1) return true;
        else return false;
    }

    /** @return the next smallest number */
    int next() {
        return ans[index++];
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值