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  */
  • 相关阅读:
    count(1)、count(*)与count(列名)的执行区别
    解析Json字符串中的指定的值
    消息队列的好处与弊端
    17 ~ express ~ 分类的显示 ,修改 和 删除
    Express ~ 获取表单 get 和 post 提交方式传送参数的对比
    16 ~ express ~ 添加博客分类
    JS ~ Promise 对象
    JS ~ Promise.reject()
    JS ~ 返回上一步
    PHP ~ 通过程序删除图片,同时删除数据库中的图片数据 和 图片文件
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4860157.html
Copyright © 2011-2022 走看看