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  */
  • 相关阅读:
    Angularjs中的ng-class
    AngularJS 的表单验证
    Eclipse更新慢、插件安装慢解决方案zz
    PSD的单位及计算方法[转]
    .NET控件名称缩写一览表 zz
    C#Stopwatch的简单计时zz
    VsVim的快捷键
    MySQL-mysql 8.0.11安装教程
    使用open live writer客户端写博客zz
    WPFToolkit DataGrid 使用介绍zz
  • 原文地址:https://www.cnblogs.com/birdhack/p/4196947.html
Copyright © 2011-2022 走看看