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  */
  • 相关阅读:
    第一个python的GUI程序
    vbs实现打开记事本,写入一些文字,复制然后关闭
    自己制作的autoitX的vbs脚本,用来自动配置金山毒霸2011局域网更新
    使用免费的unrar.exe解压rar文件
    初学写的几个autoit小程序
    vba调用AutoItX3的Activex控件,实现doc2Html源码
    网页制作相关工具
    vbs自动登陆115网盘代码
    深搜和宽搜的c++实现
    入职一个月有感
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4860157.html
Copyright © 2011-2022 走看看