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.

    其实这道题的方法就是用迭代来中序遍历BST,用一个栈来模拟。为什么用迭代,因为迭代才可以这样一步一步地输出next元素,递归都是一口气输出完。

    迭代用stack,栈的最大高度就是树的高度。

    我对这道题唯一有疑问的地方在于next()的average时间复杂度要是O(1),这里average值得推敲,因为不是每次next()时间复杂度都是O(1)的。

    因为一个node pop()之后,需要把它右子树node入栈,不仅如此,还需要沿着右子树node的左子树一路push下去,直到这一路全部入栈。这样做我不确定时间复杂度是O(1), 因为worst case时间复杂度可以到O(N). 比如:

                               1

                                 

                                  2

                                 /

                               3

                             /

                           4

    1节点pop()了之后,需要把2、3、4节点依次入栈,该次复杂度达到了O(N)。但是转念想想,4、3、2出栈的时候时间复杂度都是O(1),所以average的情况可以算是O(1)吧,值得推敲。一般不是这么极端的例子,1节点右子树节点2的左节点这一路应该是常数个节点,所以average入栈时间应该是O(1)

     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> st;
    13 
    14     public BSTIterator(TreeNode root) {
    15         st = new Stack<TreeNode>();
    16         pushLeft(root);
    17     }
    18     
    19     public void pushLeft(TreeNode root) {
    20         while (root != null) {
    21             st.push(root);
    22             root = root.left;
    23         }
    24     }
    25 
    26     /** @return whether we have a next smallest number */
    27     public boolean hasNext() {
    28         return !st.isEmpty();
    29     }
    30 
    31     /** @return the next smallest number */
    32     public int next() {
    33         TreeNode current = st.pop();
    34         pushLeft(current.right);
    35         return current.val;
    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  */
  • 相关阅读:
    TCP拥塞控制算法 — CUBIC的补丁(二)
    TCP拥塞控制算法 — CUBIC的补丁(四)
    Class chart
    Class array
    Bool to int
    using in the function
    unsafe
    resources contain {0}
    Using Nullable Types
    Microsoft.Ink namespace
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4254863.html
Copyright © 2011-2022 走看看