zoukankan      html  css  js  c++  java
  • [leetcode] Binary Search Tree Iterator

    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的最左节点就行了,不明白那个构造函数有什么意义。上网搜了才明白,是要将BST树排序,使得直接输出的时候时间和空间复杂度很低,构造函数就相当于是一个排序了。题目明白了,就会做了。利用BST树本身的特点,按照中序遍历的方法将节点的值保存在一个vector中,容器里面的元素就是从小到大排列的,只要容器非空,就一定有最小值。因此我的解法就是一个中序遍历二叉树。

    题解:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    public:
        vector<int> path;
        void inorder(TreeNode *root) {
            if(root) {
                inorder(root->left);
                path.push_back(root->val);
                inorder(root->right);
            }
        }
        BSTIterator(TreeNode *root) {
            inorder(root);
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            if(path.size()==0)
                return false;
            else
                return true;
        }
    
        /** @return the next smallest number */
        int next() {
            int res = path[0];
            path.erase(path.begin());
            return res;
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */
    View Code

    后话:

    我的做法有两个问题。第一个是中序遍历贪图代码简单用的是递归,相对费时一些。第二个是其实有更好地方法(方法二),不需要中序遍历完整个二叉树。

  • 相关阅读:
    mysql之存储过程
    Artificial Intelligence in Finance
    7 Exciting Uses of Machine Learning in FinTech
    Machine Learning in Finance – Present and Future Applications
    AI AND THE BOTTOM LINE: 15 EXAMPLES OF ARTIFICIAL INTELLIGENCE IN FINANCE
    5 Ways AI is Transforming the Finance Industry
    图学Kubernetes
    Free Professional Resume Examples and Writing Tips
    npm和yarn的淘宝镜像添加
    世界最具影响力的十大管理大师
  • 原文地址:https://www.cnblogs.com/jiasaidongqi/p/4226201.html
Copyright © 2011-2022 走看看