zoukankan      html  css  js  c++  java
  • 二叉查找树迭代器 · Binary Search Tree Iterator

    [抄题]:

    设计实现一个带有下列属性的二叉查找树的迭代器:

    • 元素按照递增的顺序被访问(比如中序遍历)
    • next()hasNext()的询问操作要求均摊时间复杂度是O(1)

    对于下列二叉查找树,使用迭代器进行中序遍历的结果为 [1, 6, 10, 11, 12]

      10
     /    
    1      11
            
      6       12

    [思维问题]:

    [一句话思路]:

    有next就全部进入stack并设末尾为空,同时有没有和stack的结果相反

    弹出一个点的同时,next要设置成cur.right,重新入栈。因为next需要往下传。

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 先定义一个AddNodeToStack方法,能入栈的先都入栈

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

    [总结]:

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构,为什么不用别的数据结构]:

    stack:

    左边先进先出,再压右边。

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    整数或其他数据类型的Peeking Iterator,弹出peek

    public class BSTIterator {
    
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode next = null;
        void addNodeToStack(TreeNode root) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
        }
        public BSTIterator(TreeNode root) {
            next = root;
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            if (next != null) {
                addNodeToStack(next);
                next = null;
            }
            return !stack.isEmpty();
        }
    
        /** @return the next smallest number */
        public int next() {
            if (! hasNext()) {
                return 0;
            }
            TreeNode cur = stack.pop();
            next = cur.right;
            return cur.val;
        }
    }
    View Code
  • 相关阅读:
    linux 服务发布脚本升级,远程发布,指定拉取远程dev,test等分支代码
    linux 执行脚本1.补充命令 2.后台执行
    centos7 操作防火墙
    复制目录及其子目录下所有文件DOC
    总结
    nmon监控与 nmon analyser分析
    nginx配置文服
    单字段去重 distinct 返回其他多个字段
    二维数组怎样进行遍历
    Socket与URL通信比较
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8379263.html
Copyright © 2011-2022 走看看