Advertisement
HXXXXJ

173. Binary Search Tree Iterator

Feb 10th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.89 KB | None | 0 0
  1. class BSTIterator {
  2.     var stack = [TreeNode]()
  3.     init(_ root: TreeNode?) {
  4.         guard let root = root else{ return }
  5.         pushLeft(root)
  6.     }
  7.    
  8.     private func pushLeft(_ node : TreeNode){
  9.         var runner = node
  10.         stack.append(node)
  11.         while runner.left != nil{
  12.             stack.append(runner.left!)
  13.             runner = runner.left!
  14.         }
  15.     }
  16.    
  17.     /** @return the next smallest number */
  18.     //每次next 的时候 pushLeft
  19.     func next() -> Int {
  20.         if stack.count > 0 {
  21.             let cur = stack.removeLast()
  22.             if let right = cur.right{
  23.                 pushLeft(right)
  24.             }
  25.             return cur.val
  26.         }
  27.         return 0
  28.     }
  29.    
  30.     /** @return whether we have a next smallest number */
  31.     //只要stack不空都说明还有东西
  32.     func hasNext() -> Bool {
  33.         return stack.count > 0
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement