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

    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.

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    在构造器中,中序遍历所有节点,加入队列中,然后操作队列就行。

     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 
    13     Queue<Integer> queue; 
    14     public BSTIterator(TreeNode root) {
    15         queue = new LinkedList<Integer>();
    16         midOrder(root);
    17 
    18     }
    19 
    20     private void midOrder(TreeNode root) {
    21         if (root == null) {
    22             return;
    23         }
    24             midOrder(root.left);
    25             queue.add(root.val);
    26             midOrder(root.right);
    27     }
    28 
    29 
    30     /** @return whether we have a next smallest number */
    31     public boolean hasNext() {
    32         return !queue.isEmpty();
    33     }
    34 
    35     /** @return the next smallest number */
    36     public int next() {
    37         return queue.poll();
    38     }
    39 }
    40 
    41 /**
    42  * Your BSTIterator will be called like this:
    43  * BSTIterator i = new BSTIterator(root);
    44  * while (i.hasNext()) v[f()] = i.next();
    45  */
  • 相关阅读:
    java四种线程池类型以及可选择的阻塞队列
    复习-java向上转型
    synchronized 加在方法和代码块底层实现区别
    synchronized 和 lock 的区别
    hashmap-put方法过程
    mybatis-防止sql注入
    synchronized-粗略过程
    消息队列-观察者模式和发布订阅模式区别
    复习-进程的调度算法
    Chocolatey
  • 原文地址:https://www.cnblogs.com/birdhack/p/4196947.html
Copyright © 2011-2022 走看看