@@ -34,8 +34,8 @@ Here's an example of this operation in code:
34
34
``` swift
35
35
extension BinaryNode {
36
36
// 1
37
- private var splitter: String { return " ," }
38
- private var nilNode: String { return " nil" }
37
+ fileprivate var splitter: String { return " ," }
38
+ fileprivate var nilNode: String { return " nil" }
39
39
40
40
// 2
41
41
var encodedString: String {
@@ -98,19 +98,32 @@ These details will shape your `decode` operation. Here's a possible implementati
98
98
``` swift
99
99
extension BinaryTree {
100
100
101
+ // 1
101
102
static func decode <Element >(from string : String ) -> BinaryNode<Element >? {
102
103
let array = string.split (separator : " ," )
103
- let deque: Deque<String > = array
104
- return decode (from : deque)
104
+ return decode (from : array)
105
105
}
106
106
107
- static func decode <Elements : RangeReplaceableCollection >(from deque : RangeReplaceableCollection )
107
+ // 2
108
+ static func decode <Elements : Sequence >(from sequence : Sequence )
108
109
-> BinaryNode< Elements .Element >? {
109
110
111
+ guard let value = sequence.first else { return nil }
112
+ if value == nilNode {
113
+ return nil
114
+ } else {
115
+ let node = BinaryNode< Elements .Element > (value : value)
116
+ node.leftChild = decode (from : AnySequence < Elements .Element > (sequence.dropFirst ()))
117
+ node.rightChild = decode (from : AnySequence < Elements .Element > (sequence.dropFirst ()))
118
+ }
110
119
}
111
120
}
112
121
```
113
122
123
+ Here's a high level overview of the above code:
124
+
125
+ 1 . Takes a ` String ` , and uses ` split ` to partition the contents of ` string ` into an array based on the ` "," ` character.
126
+ 2 . Takes any ` Sequence ` type and recursively creates a binary tree based on the rules declared in the encoding operation.
114
127
115
128
116
129
0 commit comments