• 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     private Stack<TreeNode> stack = new Stack<TreeNode>();
    13     public BSTIterator(TreeNode root) {
    14         pushAll(root);
    15     }
    16 
    17     /** @return whether we have a next smallest number */
    18     public boolean hasNext() {
    19         return !stack.isEmpty();
    20     }
    21 
    22     /** @return the next smallest number */
    23     public int next() {
    24         TreeNode node = stack.pop();
    25         pushAll(node.right);
    26         return node.val;
    27         
    28     }
    29     private void pushAll(TreeNode node){
    30         while(node != null){
    31             stack.push(node);
    32             node = node.left;
    33         }
    34             
    35     }
    36 }
    37 
    38 /**
    39  * Your BSTIterator will be called like this:
    40  * BSTIterator i = new BSTIterator(root);
    41  * while (i.hasNext()) v[f()] = i.next();
    42  */
  • 相关阅读:
    多属性量化决策模型
    对称加密与非对称加密
    子网掩码
    网络安全
    万维网WWW、电子邮件email与文件传输FTP
    DHCP协议
    DNS协议
    ARP协议与RARP协议
    springboot WebSocket的使用
    Java调用Python的两种方式
  • 原文地址:https://www.cnblogs.com/zle1992/p/8397902.html
Copyright © 2020-2023  润新知