You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Encode and Decode Tree/readme.md
+73-4Lines changed: 73 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -33,17 +33,86 @@ Here's an example of this operation in code:
33
33
34
34
```swift
35
35
extensionBinaryNode {
36
+
// 1
37
+
privatevar splitter: String { return"," }
38
+
privatevar nilNode: String { return"nil" }
39
+
40
+
// 2
36
41
var encodedString: String {
37
42
var str =""
38
-
preOrderTraversal { str.append($0) }
43
+
preOrderTraversal { data in
44
+
iflet data = data {
45
+
let string =String(describing: data)
46
+
str.append(string)
47
+
} else {
48
+
str.append(nilNode)
49
+
}
50
+
str.append(splitter)
51
+
}
39
52
return str
40
53
}
41
54
42
-
funcpreOrderTraversal(visit: (T) -> ()) {
55
+
// 3
56
+
funcpreOrderTraversal(visit: (T?) -> ()) {
43
57
visit(data)
44
-
leftChild?.preOrderTraversal(visit: visit)
45
-
rightChild?.preOrderTraversal(visit: visit)
58
+
59
+
iflet leftChild = leftChild {
60
+
leftChild.preOrderTraversal(visit: visit)
61
+
} else {
62
+
visit(nil)
63
+
}
64
+
65
+
iflet rightChild = rightChild {
66
+
rightChild.preOrderTraversal(visit: visit)
67
+
} else {
68
+
visit(nil)
69
+
}
46
70
}
47
71
}
48
72
```
49
73
74
+
Here's a high level overview of the above code:
75
+
76
+
1.`splitter` is a way to distinguish the nodes in a string. To illustrate its importance, consider the following encoded string "banana". How did the tree structure look like before encoding? Without the `splitter`, you can't tell.
77
+
78
+
2.`encodedString` is the result of the encoding process. Returns a string representation of the tree. For example: "ba,nana,nil" represents a tree with two nodes - "ba" and "nana" - in pre-order format.
79
+
80
+
3. It is interesting to note that this pre-order traversal implementation also emits `nil` values in place of absent children.
81
+
82
+
## Decoding
83
+
84
+
Your decoding strategy is the exact opposite of your encoding strategy. You'll take an encoded string, and turn it back into your binary tree.
85
+
86
+
Your encoding strategy followed the following rules:
87
+
88
+
1. The result of the encoding will be a `String` object.
89
+
2. You'll encode using *pre-order* traversal.
90
+
91
+
The implementation also added a few important details:
92
+
93
+
* node values are separated by `,`
94
+
*`nil` children are denoted by the `nil` string
95
+
96
+
These details will shape your `decode` operation. Here's a possible implementation:
0 commit comments