LeetCode | Binary Search Tree Iterator

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013033845/article/details/52399951

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.

有趣的一道题。

让二叉搜索树实现迭代器。

听起来就是重写hasNext函数啊。

那就写呗,拍成一个队列,然后直接就可以遍历了。

然后万万没想到的一点是,将递归写在了构造函数里面!!!

大写的尴尬,一直无法正确输出数据,直到后来发现如果进入了构造函数里,就是一个新的Q,所以不要写在构造函数里就好了。

另这正确的解法是利用一个栈,其实和自己写中序遍历的时候很像,只不过将两部分分开了。

这样的题目还挺有意思的~

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    // queue<TreeNode*> Q;
    stack<TreeNode*> Q;
    BSTIterator(TreeNode *root) {
        //太特么尴尬了
        // Inorder(root);
        // if(!root) return;
        // BSTIterator(root->left);
        // Q.push(root);
        // // Q.push(new TreeNode(root->val));
        // BSTIterator(root->right);
        //这个大小始终是1
        // printf("val %d size %d\n",root->val,Q.size());
        Lorder(root);
    }
    
    //向左遍历
    void Lorder(TreeNode* root){
        if(!root) return;
        if(root->left){
            Q.push(root);
            Lorder(root->left);
        }
        else Q.push(root);
    }
    
    void Inorder(TreeNode* root){
        if(!root) return;
        Inorder(root->left);
        Q.push(root);
        Inorder(root->right);
    }

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

    /** @return the next smallest number */
    int next() {
        // TreeNode* node=Q.front();
        // Q.pop();
        // return node->val;
        TreeNode* node=Q.top();
        Q.pop();
        if(node->right) Lorder(node->right);
        return node->val;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */


猜你喜欢

转载自blog.csdn.net/u013033845/article/details/52399951