|
| 1 | +import Foundation |
| 2 | + |
| 3 | +public class TreeNode<T> { |
| 4 | + public var value: T |
| 5 | + |
| 6 | + public weak var parent: TreeNode? |
| 7 | + public var children = [TreeNode<T>]() |
| 8 | + |
| 9 | + public init(value: T) { |
| 10 | + self.value = value |
| 11 | + } |
| 12 | + |
| 13 | + public func addChild(_ node: TreeNode<T>) { |
| 14 | + children.append(node) |
| 15 | + node.parent = self |
| 16 | + } |
| 17 | +} |
| 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