Created
July 11, 2015 06:32
-
-
Save xynophon/3f4226698eddcc686105 to your computer and use it in GitHub Desktop.
LeetCode Binary Search Tree Iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.*; | |
| public class BSTIterator { | |
| /** | |
| * Definition for binary tree | |
| * public class TreeNode { | |
| * int val; | |
| * TreeNode left; | |
| * TreeNode right; | |
| * TreeNode(int x) { val = x; } | |
| * } | |
| */ | |
| Stack<Integer> nums = new Stack<>(); | |
| public BSTIterator(TreeNode root) { | |
| Stack<TreeNode> nodes = new Stack<>(); | |
| TreeNode p = root; | |
| while(!nodes.isEmpty() || p != null){ | |
| if(p != null){ | |
| nodes.push(p); | |
| p = p.right; | |
| }else{ | |
| TreeNode n = nodes.pop(); | |
| nums.push(n.val); | |
| p = n.left; | |
| } | |
| } | |
| } | |
| /** @return whether we have a next smallest number */ | |
| public boolean hasNext() { | |
| if(nums.size() > 0){ | |
| return true; | |
| }else{ | |
| return false; | |
| } | |
| } | |
| /** @return the next smallest number */ | |
| public int next() { | |
| return nums.pop(); | |
| } | |
| /** | |
| * Your BSTIterator will be called like this: | |
| * BSTIterator i = new BSTIterator(root); | |
| * while (i.hasNext()) v[f()] = i.next(); | |
| */ | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment