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

    Question

    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.

    Solution

    When a problem relates to BST and sequence, we should think about in-order traversal of BST.

    We find that the original codes of Binary Tree Inorder Traversal can be modified to fit following codes.

    while (it.hasNext()) {
        System.out.println(it.next());        
    }

    Note that before print, we need to push nodes to stack first.

    Inorder traversal time complexity is O(n), so for each next() step, average time is O(1).

    And the stack costs O(h) because we either goes down or pop a node and then goes down.

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 
    11 public class BSTIterator {
    12     private Stack<TreeNode> stack;
    13     private TreeNode current;
    14 
    15     public BSTIterator(TreeNode root) {
    16         stack = new Stack<TreeNode>();
    17         current = root;
    18         while (current != null) {
    19             stack.push(current);
    20             current = current.left;
    21         }
    22         
    23     }
    24 
    25     /** @return whether we have a next smallest number */
    26     public boolean hasNext() {
    27         return (! stack.empty() || current != null);
    28     }
    29 
    30     /** @return the next smallest number */
    31     public int next() {
    32         while (current != null) {
    33             stack.push(current);
    34             current = current.left;
    35         }
    36         TreeNode tmp = stack.pop();
    37         int result = tmp.val;
    38         current = tmp.right;
    39         return result;
    40     }
    41 }
    42 
    43 /**
    44  * Your BSTIterator will be called like this:
    45  * BSTIterator i = new BSTIterator(root);
    46  * while (i.hasNext()) v[f()] = i.next();
    47  */
  • 相关阅读:
    快速排序算法图文详解(模版使用)
    数据库中事务和隔离级别解析
    详解对象的创建,布局,定位,存活判断
    SpringCloud-Ribbon:认识并配置负载均衡
    SpringCloud-Feign:接口式微服务调用
    SpringCloud-Eureka(3)集群配置和了解CAP原则
    SpringCloud-Eureka(2)服务注册与信息配置
    SpringCloud-Eureka(1)认识Eureka和初步配置
    Promise
    es6
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4860157.html
Copyright © 2011-2022 走看看