zoukankan      html  css  js  c++  java
  • Binary Search Tree Iterator

    Design an iterator over a binary search tree with the following rules:

    • Elements are visited in ascending order (i.e. an in-order traversal)
    • next() and hasNext() queries run in O(1) time in average.
    Example

    For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]

       10
     /    
    1      11
            
      6       12
    
    Challenge 

    Extra memory usage O(h), h is the height of the tree.

    Super Star: Extra memory usage O(1)

    Analyse: Recursion.

    Runtime: 25ms

     1 /**
     2  * Definition of TreeNode:
     3  * class TreeNode {
     4  * public:
     5  *     int val;
     6  *     TreeNode *left, *right;
     7  *     TreeNode(int val) {
     8  *         this->val = val;
     9  *         this->left = this->right = NULL;
    10  *     }
    11  * }
    12  * Example of iterate a tree:
    13  * BSTIterator iterator = BSTIterator(root);
    14  * while (iterator.hasNext()) {
    15  *    TreeNode * node = iterator.next();
    16  *    do something for node
    17  */
    18 class BSTIterator {
    19 public:
    20     //@param root: The root of binary tree.
    21     BSTIterator(TreeNode *root) {
    22         // write your code here
    23         inorder = inorderTraversal(root);
    24         index = 0;
    25     }
    26 
    27     //@return: True if there has next node, or false
    28     bool hasNext() {
    29         // write your code here
    30         return index < inorder.size();
    31     }
    32     
    33     //@return: return next node
    34     TreeNode* next() {
    35         // write your code here
    36         if (index >= inorder.size()) return NULL;
    37         return inorder[index++];
    38     }
    39     
    40 private:
    41     vector<TreeNode* > inorder;
    42     int index;
    43     
    44     vector<TreeNode* > inorderTraversal(TreeNode* root) {
    45         vector<TreeNode* > result;
    46         
    47         helper(result, root);
    48         return result;
    49     }
    50     
    51     void helper(vector<TreeNode* >& result, TreeNode* root) {
    52         if (!root) return;
    53         
    54         helper(result, root->left);
    55         result.push_back(root);
    56         helper(result, root->right);
    57     }
    58 };
  • 相关阅读:
    C# @符号的多种使用方法
    C#抽象工厂简单实现类
    项目总结——谈谈封装(抽象工厂+反射+缓存机制)
    C#中String类的几个方法(IndexOf、LastIndexOf、Substring)
    String str 与 String str=new String("") 区别
    sql面试题
    [bzoj2038]莫队算法学习
    分治算法初步
    线段树训练
    [poj2104]可持久化线段树入门题(主席树)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5851559.html
Copyright © 2011-2022 走看看