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  */
  • 相关阅读:
    pillow模块的用法 + 随机验证码
    jquery文件阅读器 显示需要上传图片的预览功能
    pycharm永久激活方式
    pycharm汉化
    10.25网络编程到并发编程
    10.15 迭代器,生成器到常用模块的小结
    10.14 面向对象小结
    十一天学习内容总结大纲
    pip镜像源的替换
    前端jQuery导入方式
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9810155.html
Copyright © 2011-2022 走看看