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

    Analyse: Inorder traversal of BST. 

    Runtime: 28ms.

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class BSTIterator {
    11 public:
    12     BSTIterator(TreeNode *root) {
    13         inorder(root);
    14     }
    15 
    16     /** @return whether we have a next smallest number */
    17     bool hasNext() {
    18         return !qu.empty();
    19     }
    20 
    21     /** @return the next smallest number */
    22     int next() {
    23         int nextSmallest = qu.front();
    24         qu.pop();
    25         return nextSmallest;
    26     }
    27 private:
    28     queue<int> qu;
    29     
    30     void inorder(TreeNode* root) {
    31         if(!root) return;
    32         
    33         inorder(root->left);
    34         qu.push(root->val);
    35         inorder(root->right);
    36     }
    37 };
    38 
    39 /**
    40  * Your BSTIterator will be called like this:
    41  * BSTIterator i = BSTIterator(root);
    42  * while (i.hasNext()) cout << i.next();
    43  */
  • 相关阅读:
    jar 常用操作
    linux 加载新的磁盘(卷组)
    apache 代理配置
    spring boot datasource 参数设置
    svn 常用命令
    最详细的maven教程
    centos 用户组操作
    ubuntu命令行操作mysql常用操作
    Ruby-Clamp
    maven使用备忘
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5755269.html
Copyright © 2011-2022 走看看