@@ -2,16 +2,57 @@ import Foundation
22
33public class TreeNode < T> {
44 public var value : T
5-
5+
66 public weak var parent : TreeNode ?
77 public var children = [ TreeNode < T > ] ( )
8-
8+
99 public init ( value: T ) {
1010 self . value = value
1111 }
12-
12+
1313 public func addChild( _ node: TreeNode < T > ) {
1414 children. append ( node)
1515 node. parent = self
1616 }
1717}
18+
19+ /* Checks the node's value property, if there is no match, check the child nodes.
20+ Repeat the same process recursively */
21+ extension TreeNode where T: Equatable {
22+ func search( _ value: T ) -> TreeNode ? {
23+ if value == self . value {
24+ return self
25+ }
26+ for child in children {
27+ if let found = child. search ( value) {
28+ return found
29+ }
30+ }
31+ return nil
32+ }
33+ }
34+
35+ // The code below can be used for testing
36+ let tree = TreeNode < String > ( value: " animals " )
37+
38+ let reptilesNode = TreeNode < String > ( value: " reptiles " )
39+ let mammalsNode = TreeNode < String > ( value: " mammals " )
40+
41+ let lizardsNode = TreeNode < String > ( value: " lizards " )
42+ let snakesNode = TreeNode < String > ( value: " snakes " )
43+
44+ let dogsNode = TreeNode < String > ( value: " dogs " )
45+ let humansNode = TreeNode < String > ( value: " humans " )
46+
47+ tree. addChild ( reptilesNode)
48+ tree. addChild ( mammalsNode)
49+
50+ reptilesNode. addChild ( lizardsNode)
51+ reptilesNode. addChild ( snakesNode)
52+
53+ mammalsNode. addChild ( dogsNode)
54+ mammalsNode. addChild ( humansNode)
55+
56+ print ( tree. search ( " humans " ) ? . value)
57+ print ( tree. search ( " lizards " ) ? . value)
58+ print ( tree. search ( " dragons " ) ? . value)
0 commit comments