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

  • 相关阅读:
    关系运算符重载
    一元运算符重载
    二元运算符重载
    重载函数和重载运算符
    Linux之文件通信
    Linux进程通信之mmap
    Linux之创建多个子进程
    内联函数
    静态成员
    this指针
  • 原文地址:https://www.cnblogs.com/kykai/p/11643683.html
Copyright © 2011-2022 走看看