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  */
  • 相关阅读:
    java中并发包简要分析01
    java中的集合包简要分析
    多线程学习——终结任务
    大型高并发高负载网站的系统架构
    An expression evaluator
    java公式解析器学习与开发(2)——前缀表达式
    java公式解析器学习与开发(1)
    程序员遇到bug时常见的30种反应
    图论--SCC强连通缩点--Tarjan
    图论--割边--Tarjan模板
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4860157.html
Copyright © 2011-2022 走看看