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) 。 

      

  • 相关阅读:
    OC基础数据类型-NSData-NSMutableData-NSString
    python学习:格式化输出
    python学习:修改字符串大小写
    python学习:输出九九乘法表
    python学习:输入中文
    python学习:缩进
    python学习:注释、获取用户输入、字符串拼接、运算符、表达式
    python学习:条件语句if、else
    python学习:常量和变量
    hdoj1584 蜘蛛牌 (区间型动态规划)
  • 原文地址:https://www.cnblogs.com/niuyourou/p/13342090.html
Copyright © 2011-2022 走看看