• 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  */
  • 相关阅读:
    使用RequireJS优化Web应用前端
    基线样式
    css层叠顺序
    摘录android工具类
    android中相关的图形类
    Google Android SDK开发范例------------20141119
    将博客搬至CSDN
    LightOJ1356 最大独立集 HK算法 素数分解
    求二分图最大匹配——Hopcroft-Krap算法
    HDU 6333 莫队分块 + 逆元打表求组合数
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4860157.html
Copyright © 2020-2023  润新知