diff --git a/leetcode/design/BSTIterator.java b/leetcode/design/BSTIterator.java new file mode 100644 index 00000000..7691d50d --- /dev/null +++ b/leetcode/design/BSTIterator.java @@ -0,0 +1,41 @@ +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + +public class BSTIterator { + private static Queue queue; + + public BSTIterator(TreeNode root) { + queue = new LinkedList(); + inorderTraversal(root); + } + + /** @return whether we have a next smallest number */ + public boolean hasNext() { + return !(queue.size()==0); + } + + /** @return the next smallest number */ + public int next() { + return queue.poll(); + } + + private static void inorderTraversal(TreeNode node){ + if(node==null) return; + inorderTraversal(node.left); + queue.add(node.val); + inorderTraversal(node.right); + } +} + +/** + * Your BSTIterator will be called like this: + * BSTIterator i = new BSTIterator(root); + * while (i.hasNext()) v[f()] = i.next(); + */ \ No newline at end of file