zoukankan      html  css  js  c++  java
  • Leetcode173 二叉搜索树迭代器 链表与栈

     

      借助链表实现:

        class BSTIterator {
            final List<TreeNode> treeList;
            int currentPoint;
            int length;
    
            public BSTIterator(TreeNode root) {
                treeList = new LinkedList<TreeNode>();
                toList(root);
                currentPoint = 0;
                length = treeList.size();
            }
    
            private final void toList(TreeNode node) {
                if (node == null) {
                    return;
                }
                toList(node.left);
                treeList.add(node);
                toList(node.right);
            }
    
            /**
             * @return the next smallest number
             */
            public final int next() {
                if (currentPoint == length) {
                    throw new RuntimeException("Out of index " + currentPoint + " with length of " + length);
                }
                currentPoint++;
                return treeList.get(currentPoint - 1).val;
            }
    
            /**
             * @return whether we have a next smallest number
             */
            public final boolean hasNext() {
                return currentPoint < length;
            }
        }

      借助栈实现:

        class BSTIterator2 {
            final Stack<TreeNode> stack;
    
            public BSTIterator2(TreeNode root) {
                stack = new Stack<TreeNode>();
                pushLeft(root);
            }
    
            private void pushLeft(TreeNode node) {
                if (node == null) {
                    return;
                }
                while (node != null) {
                    stack.push(node);
                    node = node.left;
                }
            }
    
            /**
             * @return the next smallest number
             */
            public final int next() {
                if (stack.size() == 0) {
                    return -1;
                }
                TreeNode node = stack.pop();
                if (node.right != null) {
                    pushLeft(node.right);
                }
                return node.val;
            }
    
            /**
             * @return whether we have a next smallest number
             */
            public final boolean hasNext() {
                return stack.size() != 0;
            }
        }

      借助栈模拟递归过程,将空间复杂度由 O(N) 降低到了 O(H)。且最坏情况下时间复杂度为 O(H) 。 

      

  • 相关阅读:
    java 反射
    java 面试题
    Java构造和解析Json数据的两种方法详解一
    JAVA UUID 生成
    tomcat 插件
    webstorm 激活码
    maven环境搭建
    svn 安装网站
    2015.6.30 反弹的教训(想做T)
    2015.6.15 惨跌开始的反思
  • 原文地址:https://www.cnblogs.com/niuyourou/p/13342090.html
Copyright © 2011-2022 走看看