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.

    链接: http://leetcode.com/problems/binary-search-tree-iterator/

    6/20/2017
    7ms, 23%

    有想法,但是代码主要是看别人的

    思路是把inorder traversal拆开,运行next时候把右边的压进栈

     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;
    13     public BSTIterator(TreeNode root) {
    14         stack = new Stack<TreeNode>();
    15         inorder(root);
    16     }
    17     
    18     private void inorder(TreeNode root) {
    19         while (root != null) {
    20             stack.push(root);
    21             root = root.left;
    22         }
    23     }
    24 
    25     /** @return whether we have a next smallest number */
    26     public boolean hasNext() {
    27         return !stack.isEmpty();
    28     }
    29 
    30     /** @return the next smallest number */
    31     public int next() {
    32         if (hasNext()) {
    33             TreeNode top = stack.pop();
    34             if (top.right != null) {
    35                 inorder(top.right);
    36             }
    37             return top.val;
    38         }
    39         return -1;
    40     }
    41 }
    42 
    43 /**
    44  * Your BSTIterator will be called like this:
    45  * BSTIterator i = new BSTIterator(root);
    46  * while (i.hasNext()) v[f()] = i.next();
    47  */

    针对时间复杂度的解释:

    The average time complexity of next() function is O(1) indeed in your case. As the next function can be called n times at most, and the number of right nodes in self.pushAll(tmpNode.right) function is maximal n in a tree which has n nodes, so the amortized time complexity is O(1).

    https://discuss.leetcode.com/topic/6575/my-solutions-in-3-languages-with-stack

    更多讨论

    https://discuss.leetcode.com/category/181/binary-search-tree-iterator

  • 相关阅读:
    索引
    静态成员实例
    异常实例
    继承实例
    构造函数实例
    verilog时序优化
    verilog语法笔记
    Idelay进行时序调节
    Vivado综合属性:ASYNC_REG
    verilog分频
  • 原文地址:https://www.cnblogs.com/panini/p/7055936.html
Copyright © 2011-2022 走看看