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) 。
当你看清人们的真相,于是你知道了,你可以忍受孤独