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: find the next smallest number in the BST and realize the iteration process. The same as inorder traversal.

    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     stack<TreeNode* > stk;
    13     BSTIterator(TreeNode *root) {
    14         while(root){
    15             stk.push(root);
    16             root = root->left;
    17         }
    18     }
    19 
    20     /** @return whether we have a next smallest number */
    21     bool hasNext() {
    22         return !stk.empty();
    23     }
    24 
    25     /** @return the next smallest number */
    26     int next() {
    27         TreeNode* temp = stk.top();
    28         stk.pop();
    29         int nextMin = temp->val;
    30         temp = temp->right;
    31         while(temp){
    32             stk.push(temp);
    33             temp = temp->left;
    34         }
    35         return nextMin;
    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  */
  • 相关阅读:
    Spring配置多个数据源
    虚拟机内存结构
    Java中sleep,wait,yield,join的区别
    Java的四种引用方式
    Java 中的泛型详解-Java编程思想
    Java RTTI和反射
    linux 分析java 线程状态
    小容量的byteBuffer 读取大文本
    @Conditional 原理
    替换字符串占位符
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4699006.html
Copyright © 2011-2022 走看看