Binary Tree Traversal
BST iterator (Inorder traversal)
ref: https://leetcode.com/problems/binary-search-tree-iterator/
public class BSTIterator { private Stack<TreeNode> stack; private TreeNode prev; public BSTIterator(TreeNode root) { prev = null; stack = new Stack<TreeNode>(); while (root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty() || (prev != null && prev.right != null); } /** @return the next smallest number */ public int next() { if (prev != null && prev.right != null) { prev = prev.right; while (prev != null) { stack.push(prev); prev = prev.left; } } prev = stack.pop(); return prev.val; } }