Leetcode 173: Binary Search Tree Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 11 public class BSTIterator { 12 private Stack<TreeNode> stack = new Stack<TreeNode>(); 13 14 public BSTIterator(TreeNode root) { 15 while (root != null) 16 { 17 stack.Push(root); 18 root = root.left; 19 } 20 } 21 22 /** @return whether we have a next smallest number */ 23 public bool HasNext() { 24 return stack.Count != 0; 25 } 26 27 /** @return the next smallest number */ 28 public int Next() { 29 var top = stack.Pop(); 30 31 if (top.right != null) 32 { 33 var n = top.right; 34 35 while (n != null) 36 { 37 stack.Push(n); 38 n = n.left; 39 } 40 } 41 42 return top.val; 43 } 44 } 45 46 /** 47 * Your BSTIterator will be called like this: 48 * BSTIterator i = new BSTIterator(root); 49 * while (i.HasNext()) v[f()] = i.Next(); 50 */

浙公网安备 33010602011771号