zoukankan      html  css  js  c++  java
  • LC 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.

    Example:

    BSTIterator iterator = new BSTIterator(root);
    iterator.next();    // return 3
    iterator.next();    // return 7
    iterator.hasNext(); // return true
    iterator.next();    // return 9
    iterator.hasNext(); // return true
    iterator.next();    // return 15
    iterator.hasNext(); // return true
    iterator.next();    // return 20
    iterator.hasNext(); // return false

    参考答案

    class BSTIterator {
    private:
        stack<TreeNode*> st;
        
        public:
        BSTIterator(TreeNode* root) {
            foo(root);
        }
        
        /** @return the next smallest number */
        int next() {
            TreeNode* temp = st.top();
            st.pop();
            foo(temp->right);
            return temp->val;
        }
        
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return !st.empty();
        }
        
        void foo(TreeNode* root){
            for(;root!=NULL;st.push(root),root=root->left);
        }
    };

    答案解析

    建立一个新的stack,其中存储包括自身的左孩子,这意味着整条树都存在里面,而最上边的永远是树的最左孩子。

    next函数,就是把最上面的弹出来,将该点的右孩子(以及它的所有左孩子)给存了,从而保证最小的在第一个。

  • 相关阅读:
    1032. Sharing (25)
    1031. Hello World for U (20)
    1030. Travel Plan (30)
    1029. Median (25)
    1028. List Sorting (25)
    1026. Table Tennis (30)
    win10 tortoiseSVN文件夹及文件图标不显示解决方法
    qrcode.react和jquery.qrcode生成二维码
    js来获取所有屏幕适配的总结
    handsontable整理
  • 原文地址:https://www.cnblogs.com/kykai/p/11643683.html
Copyright © 2011-2022 走看看