Advertisement
sweet1cris

Untitled

Jan 9th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.82 KB | None | 0 0
  1. public class BSTIterator {
  2.     private Stack<TreeNode> stack = new Stack<>();
  3.     TreeNode next = null;
  4.     void AddNodeToStack(TreeNode root) {
  5.         while (root != null) {
  6.             stack.push(root);
  7.             root = root.left;
  8.         }
  9.     }
  10.    
  11.     // @param root: The root of binary tree.
  12.     public BSTIterator(TreeNode root) {
  13.         next = root;
  14.     }
  15.  
  16.     //@return: True if there has next node, or false
  17.     public boolean hasNext() {
  18.         if (next != null) {
  19.             AddNodeToStack(next);
  20.             next = null;
  21.         }
  22.         return !stack.isEmpty();
  23.     }
  24.    
  25.     //@return: return next node
  26.     public TreeNode next() {
  27.         if (!hasNext()) {
  28.             return null;
  29.         }
  30.         TreeNode cur = stack.pop();
  31.         next = cur.right;
  32.         return cur;
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement