为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode173. 二叉搜索树迭代器 | Binary Search Tree Iterator

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10145246.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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.


实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

注意: next() 和hasNext() 操作的时间复杂度是O(1),并使用 O(h) 内存,其中 是树的高度。


212ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 
15 class BSTIterator {
16     
17     //we need a storage to store the values
18     //let's define an array
19     private var storage = [Int]()
20     
21     //we also need a counter to run the iterator
22     private var counter = -1
23     
24     //we need to traverse in an inorder fashion and store the elements
25     //in the storage
26     private func traverseInorder(_ root: TreeNode?) {
27         if root == nil { return }
28         traverseInorder(root!.left)
29         storage.append(root!.val)
30         traverseInorder(root!.right)
31     }
32 
33     init(_ root: TreeNode?) {
34         traverseInorder(root)
35     }
36     
37     /** @return the next smallest number */
38     func next() -> Int {
39         if hasNext() {
40             counter += 1
41             return storage[counter]
42         }
43         return -1
44     }
45     
46     /** @return whether we have a next smallest number */
47     func hasNext() -> Bool {
48         if counter < storage.count - 1{
49             return true
50         }
51         return false
52     }
53 }

216ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 
15 class BSTIterator {
16 
17     private var stack = [TreeNode]()
18 
19     // MARK: - Initialization
20 
21     init(_ root: TreeNode?) {
22         var curr = root
23         while let node = curr {
24             stack.append(node)
25             curr = node.left
26         }
27     }
28 
29     // MARK: - Iterator methods
30 
31     func next() -> Int {
32         guard let node = stack.popLast() else { fatalError("No values to iterate over") }
33         var curr = node.right
34         while let new = curr {
35             stack.append(new)
36             curr = new.left
37         }
38 
39         return node.val
40     }
41 
42     func hasNext() -> Bool {
43         return !stack.isEmpty
44     }
45 }
46 
47 /**
48  * Your BSTIterator object will be instantiated and called as such:
49  * let obj = BSTIterator(root)
50  * let ret_1: Int = obj.next()
51  * let ret_2: Bool = obj.hasNext()
52  */

220ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 
15 class BSTIterator {
16 
17       var nodesArray = [TreeNode?]()
18   
19       init(_ root: TreeNode?) {
20 
21         var node = root
22 
23         while node != nil {
24           nodesArray.append(node)
25           node = node?.left
26         }
27       }
28 
29       /** @return the next smallest number */
30       func next() -> Int {
31 
32         var lastNode = nodesArray.removeLast()
33         let nextValue = lastNode?.val ?? 0
34 
35         lastNode = lastNode?.right
36 
37         while lastNode != nil {
38           nodesArray.append(lastNode)
39           lastNode = lastNode?.left
40         }
41 
42         return nextValue
43       }
44 
45       /** @return whether we have a next smallest number */
46       func hasNext() -> Bool {
47         return !nodesArray.isEmpty
48       }
49 }
50 
51 /**
52  * Your BSTIterator object will be instantiated and called as such:
53  * let obj = BSTIterator(root)
54  * let ret_1: Int = obj.next()
55  * let ret_2: Bool = obj.hasNext()
56  */

224ms

 1 class BSTIterator {
 2     var stack : Array<TreeNode?> = []
 3     init(_ root: TreeNode?) {
 4         addElements(root)
 5     }
 6     
 7     /** @return the next smallest number */
 8     func next() -> Int {
 9         let node = stack.popLast()!
10         addElements(node?.right)
11         return (node?.val)!
12     }
13     
14     /** @return whether we have a next smallest number */
15     func hasNext() -> Bool {
16         return !stack.isEmpty
17     }
18     func addElements(_ root : TreeNode?)  {
19         if nil != root {
20             var temp : TreeNode? = root
21             while nil != temp {
22                 stack.append(temp)
23                 temp = temp?.left
24             }
25         }
26     }
27 }

228ms

 1 class BSTIterator {
 2 
 3     var nodes:[TreeNode] = [TreeNode]()
 4     
 5     init(_ root: TreeNode?) {
 6         loadTree(root)
 7     }
 8     
 9     private func loadTree(_ node:TreeNode?){
10         
11         guard let node = node else{
12             return
13         }
14         
15         loadTree(node.left)
16         nodes.append(node)
17         loadTree(node.right)
18     }
19     /** @return the next smallest number */
20 
21     func next() -> Int {
22         return self.nodes.removeFirst().val
23     }
24     /** @return whether we have a next smallest number */
25 
26     func hasNext() -> Bool {
27         return self.nodes.count > 0
28     }
29 }

236ms

 1 class BSTIterator {
 2 
 3     var fakeQueue = [Int]()
 4     
 5     init(_ root: TreeNode?) {
 6         constructFakeQueue(root, &fakeQueue)
 7     }
 8     
 9     /** @return the next smallest number */
10     func next() -> Int {
11         return fakeQueue.removeFirst()
12     }
13     
14     /** @return whether we have a next smallest number */
15     func hasNext() -> Bool {
16         return fakeQueue.isEmpty == false
17     }
18     
19     // In order traversal to store vals
20     private func constructFakeQueue(_ root: TreeNode?, _ fakeQueue: inout [Int]) {
21         if root == nil {
22             return
23         }
24         
25         constructFakeQueue(root?.left, &fakeQueue)
26         fakeQueue.append((root?.val)!)
27         constructFakeQueue(root?.right, &fakeQueue)
28     }
29 }

240ms

 1 class BSTIterator {
 2     var root: TreeNode?
 3     var stack: [TreeNode?]
 4     init(_ root: TreeNode?) {
 5         self.root = root 
 6         self.stack = [TreeNode?]()
 7         helper(root)
 8     }
 9     
10     /** @return the next smallest number */
11     func next() -> Int {
12         let n = stack.removeLast()
13         helper(n!.right)
14         return n!.val
15         
16     }
17     func helper(_ root: TreeNode?) {
18         var root = root
19         while root != nil {
20             self.stack.append(root)
21             root = root!.left
22         }
23     }
24     
25     /** @return whether we have a next smallest number */
26     func hasNext() -> Bool {
27         return !stack.isEmpty
28     }
29 }

244ms

 1 class BSTIterator {
 2     
 3     //we need a storage to store the values
 4     //let's define an array
 5     private var storage = [Int]()
 6     
 7     //we also need a counter to run the iterator
 8     private var counter = -1
 9     
10     //we need to traverse in an inorder fashion and store the elements
11     //in the storage
12     private func traverseInorder(_ root: TreeNode?) {
13         if root == nil { return }
14         traverseInorder(root!.left)
15         storage.append(root!.val)
16         traverseInorder(root!.right)
17     }
18     
19     //let's also write traverseInorder iteratively
20     private func traverseInorderIt(_ root: TreeNode?) {
21         if root == nil { return }
22         var root = root
23         var stack = [TreeNode]()
24         
25         while root != nil || !stack.isEmpty {
26             if root != nil {
27                 stack.append(root!)
28                 root = root!.left
29             } else {
30                 root = stack.removeLast()
31                 storage.append(root!.val)
32                 root = root!.right
33             }
34         } 
35     }
36 
37     init(_ root: TreeNode?) {
38         //traverseInorder(root)
39         traverseInorderIt(root)
40     }
41     
42     /** @return the next smallest number */
43     func next() -> Int {
44         if hasNext() {
45             counter += 1
46             return storage[counter]
47         }
48         return -1
49     }
50     
51     /** @return whether we have a next smallest number */
52     func hasNext() -> Bool {
53         if counter < storage.count - 1{
54             return true
55         }
56         return false
57     }
58 }

264ms

 1 class BSTIterator {
 2     
 3     var all = [TreeNode]()
 4     var currentIndex = 0
 5     
 6     init(_ root: TreeNode?) {
 7         self.dfs(root)
 8     }
 9     /** @return the next smallest number */
10 
11     func next() -> Int {
12         guard self.currentIndex < self.all.count else { return -1 }
13         let next = all[self.currentIndex]
14         self.currentIndex += 1
15         return next.val
16         
17     }
18     /** @return whether we have a next smallest number */
19 
20     func hasNext() -> Bool {
21         return self.currentIndex < self.all.count
22     }
23     
24     private func dfs(_ root: TreeNode?) {
25         guard let node = root else { return }
26         dfs(node.left)
27         self.all.append(node)
28         dfs(node.right)
29     }
30 }

 

posted @ 2018-12-19 18:58  为敢技术  阅读(353)  评论(0编辑  收藏  举报