• 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.

    分析

    实现二叉查找树的迭代器;

    如题目描述,迭代器包括hasNext()和next()两个函数,其中hasNext()函数判断是否还有下一节点,next()函数返回节点元素值;且遍历顺序按照元素递增方式;

    我们知道,对于二叉查找树的中序遍历结果为递增有序;所以此题的简单解法即是得到该二叉查找树的中序遍历序列并用queue保存;然后对queue进行处理;

    AC代码

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    public:
        BSTIterator(TreeNode *root) {   
            //中序遍历该二叉查找树,得到有序序列
            inOrder(root, inOrderNodes);
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            if (!inOrderNodes.empty())
                return true;
            return false;
        }
    
        /** @return the next smallest number */
        int next() {
            TreeNode *node = inOrderNodes.front();
            inOrderNodes.pop();
            return node->val;
        }
    private:
        queue<TreeNode *> inOrderNodes;
    
        void inOrder(TreeNode *root, queue<TreeNode *> &inOrderNodes)
        {
            if (!root)
                return;
            if (root->left)
                inOrder(root->left, inOrderNodes);
    
            inOrderNodes.push(root);
    
            if (root->right)
                inOrder(root->right, inOrderNodes);
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */
  • 相关阅读:
    APP上线碰到的问题:Non-public API usage
    点语法
    strlen、strcpy、strcat的实现
    2. I/O模型基本说明
    1. 同步、异步、阻塞、非阻塞
    8. 负载均衡请求转发实现
    7.负载均衡算法
    6. Nginx配置示例-高可用集群
    5. Nginx配置示例-动静分离
    4. Nginx配置示例-负载均衡
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214724.html
Copyright © 2020-2023  润新知