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转换win下乱码txt命令
    linux下vi命令大全详细版本
    ubuntu系统如何安装adb调试环境
    LeetCode136---只出现一次的数字
    微信发朋友圈--用例设计(转)
    微服务
    LeetCode1---两数之和
    python输出
    爬楼梯,N级楼梯有多少种走法?
    list数组排序---stream
  • 原文地址:https://www.cnblogs.com/kykai/p/11643683.html
Copyright © 2011-2022 走看看