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

    思路:

    代码:

     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     private TreeNode cur;
    14     private Stack<TreeNode> stack;
    15 
    16     public BSTIterator(TreeNode root) {
    17         cur = root;
    18         stack = new Stack<>();
    19         
    20     }
    21 
    22     /** @return whether we have a next smallest number */
    23     public boolean hasNext() {
    24         if(!stack.isEmpty()|| cur!=null) return true;
    25         return false;
    26     }
    27 
    28     /** @return the next smallest number */
    29     public int next() {   
    30       while(cur!=null){
    31           stack.push(cur);
    32           cur = cur.left;
    33       }
    34         cur = stack.pop();
    35         int val = cur.val;
    36         cur = cur.right;
    37         return val;     
    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  */
  • 相关阅读:
    Your First ASP.NET 5 Application on a Mac
    vnextcn
    基于微服务的软件架构模式
    数组链表下标指针map list
    十一、从头到尾彻底解析Hash 表算法
    failed to create hive metastore database tables
    VSCode 常用插件
    HTML中块级行级元素小分类
    WEB前端程序员需要的网站整理
    UI1_HTTP下载
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9810155.html
Copyright © 2011-2022 走看看