Skip to content

Commit 959aaaf

Browse files
kelvinlauKLremlostime
authored andcommitted
More progress.
1 parent b772141 commit 959aaaf

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

Encode and Decode Tree/readme.md

+18-5
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ Here's an example of this operation in code:
3434
```swift
3535
extension BinaryNode {
3636
// 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" }
3939

4040
// 2
4141
var encodedString: String {
@@ -98,19 +98,32 @@ These details will shape your `decode` operation. Here's a possible implementati
9898
```swift
9999
extension BinaryTree {
100100

101+
// 1
101102
static func decode<Element>(from string: String) -> BinaryNode<Element>? {
102103
   let array = string.split(separator: ",")
103-
let deque: Deque<String> = array
104-
return decode(from: deque)
104+
return decode(from: array)
105105
}
106106

107-
static func decode<Elements: RangeReplaceableCollection>(from deque: RangeReplaceableCollection)
107+
// 2
108+
static func decode<Elements: Sequence>(from sequence: Sequence)
108109
-> BinaryNode<Elements.Element>? {
109110

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+
}
110119
}
111120
}
112121
```
113122

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.
114127

115128

116129

0 commit comments

Comments
 (0)