From 3e9477254f8cb629f33d3a375655810a9b694022 Mon Sep 17 00:00:00 2001 From: Pramod Gupta Date: Sun, 2 Sep 2018 09:29:56 +0530 Subject: [PATCH] Added BSTIterator implementation --- leetcode/design/BSTIterator.java | 41 ++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 leetcode/design/BSTIterator.java 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