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

    本题要求在常熟时间内完成next()操作,并且在tree的高度的空间复杂度。思路是和之前的Binary Tree Inorder Traverse一样的,采用前序遍历的思路,因为受到存储的限制,因此只有一次存储一个DFS,代码如下:

     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     Stack<TreeNode> stack = new Stack<TreeNode>();
    13     public BSTIterator(TreeNode root) {
    14         TreeNode node = root;
    15         while(node!=null){
    16             stack.push(node);
    17             node = node.left;
    18         }
    19     }
    20 
    21     /** @return whether we have a next smallest number */
    22     public boolean hasNext() {
    23         return !stack.isEmpty();
    24     }
    25 
    26     /** @return the next smallest number */
    27     public int next() {
    28         TreeNode tmp = stack.pop();
    29         int value = tmp.val;
    30         tmp = tmp.right;
    31         while(tmp!=null){
    32             stack.push(tmp);
    33             tmp = tmp.left;
    34         }
    35         return value;
    36     }
    37 }
    38 
    39 /**
    40  * Your BSTIterator will be called like this:
    41  * BSTIterator i = new BSTIterator(root);
    42  * while (i.hasNext()) v[f()] = i.next();
    43  */
  • 相关阅读:
    在关闭窗体时弹出对话框
    使应用程序在进程中消失
    禁用窗口上的关闭按钮
    洛谷P1080 国王游戏
    洛谷P1443 马的遍历
    算法竞赛入门经典第二版 随笔1
    AcWing 794. 高精度除法
    AcWing 793. 高精度乘法
    AcWing 792. 高精度减法
    AcWing 791. 高精度加法
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6608178.html
Copyright © 2011-2022 走看看