zoukankan      html  css  js  c++  java
  • 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.

    思路:

    通过中序遍历将结果保存到一个队列queue中,hasNext()判断queue是否为空,getNext()返回队列头部元素即可

     1 public class BSTIterator {
     2     private Queue<Integer> queueOfInOrder = new LinkedList<Integer>();            //保存中序遍历得到的队列
     3     public BSTIterator(TreeNode root) {
     4         InOrder(root);                                                            //中序遍历树,得到中序遍历结点队列
     5     }
     6 
     7     /** @return whether we have a next smallest number */
     8     public boolean hasNext() {
     9         if(queueOfInOrder.isEmpty())
    10             return false;                                                        //队列为空,说明已经最后一个元素
    11         return true;
    12     }
    13 
    14     /** @return the next smallest number */
    15     public int next() {
    16         Integer headOfQueue = queueOfInOrder.poll();
    17         
    18         return headOfQueue;
    19     }
    20     
    21     /**
    22      * 中序遍历树
    23      */
    24     private void InOrder(TreeNode root){
    25         if(null != root){
    26             InOrder(root.left);
    27             queueOfInOrder.add(root.val);
    28             InOrder(root.right);
    29         }
    30     }
    31 }
  • 相关阅读:
    [haoi2011]向量
    [haoi2008]硬币购物
    noi2001 [食物链]并查集p1697
    [haoi2012]容易题(数论+容斥的思想)
    p1620田忌赛马(贪心+模拟)
    p1368[扑街]广场铺砖
    [zjoi2010]网络扩容
    是时候写一篇总结了
    P1630 求和
    魔术棋子
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4196732.html
Copyright © 2011-2022 走看看