- 계층 구조 관계를 대표하는 것.
- 정렬된 데이터를 관리하는 것.
- 작동을 빠르게 확인하는 것. 등이 있다.
public class TreeNode<T> {
public var value: T
public var children: [TreeNode] = []
public weak var parent: TreeNode?
public init(_ value: T) {
self.value = value
}
public func add(_ child: TreeNode) {
children.append(child)
}
}
func makeBeverageTree() -> TreeNode<String> {
let tree = TreeNode("Beverages")
let hot = TreeNode("hot")
let cold = TreeNode("cold")
let tea = TreeNode("tea")
let coffee = TreeNode("coffee")
let chocolate = TreeNode("cocoa")
let blackTea = TreeNode("black")
let greenTea = TreeNode("green")
let chaiTea = TreeNode("chai")
let soda = TreeNode("soda")
let milk = TreeNode("milk")
let gingerAle = TreeNode("ginger ale")
let bitterLemon = TreeNode("bitter lemon")
tree.add(hot)
tree.add(cold)
hot.add(tea)
hot.add(coffee)
hot.add(chocolate)
cold.add(soda)
cold.add(milk)
tea.add(blackTea)
tea.add(greenTea)
tea.add(chaiTea)
soda.add(gingerAle)
soda.add(bitterLemon)
return tree
}
let tree = makeBeverageTree()
extension TreeNode {
public func forEachDepthFirst(visit: (TreeNode) -> Void) {
visit(self)
children.forEach {
$0.forEachDepthFirst(visit: visit)
}
}
}
Beverages
hot
tea
black
green
chai
coffee
cocoa
cold
soda
ginger ale
bitter lemon
milk
extension TreeNode {
public func forEachLevelOrder(visit: (TreeNode) -> Void) {
visit(self)
var queue = Queue<TreeNode>()
children.forEach { queue.enqueue($0) }
while let node = queue.dequeue() {
visit(node)
node.chlidren.forEach { queue.enqueue($0) }
}
}
}
Beverages
hot
cold
tea
coffee
cocoa
soda
milk
black
green
chai
ginger ale
bitter lemon
extension TreeNode where T: Equtable {
public func search(_ value: T) -> TreeNode? {
var result: TreeNode?
forEachLevelOrder { node in
if node.value == value {
return = node
}
}
return result
}
}
extension TreeNode {
public func forEachLevelOrderPrint() {
var queue = Queue<TreeNode>()
var nodeLeftInCurrentLevel = 0
queue.enqueue(self)
while !queue.isEmpty {
nodeLeftInCurrentLevel = queue.count
while nodeLeftInCurrentLevel > 0 {
guard let node = queue.dequeue() else { break }
print("\(node.value)", terminator: "")
node.children.forEach { queue.enqueue($0) }
nodeLeftInCurrentLevel -= 1
}
print()
}
}
}
Beverages
hot cold
tea coffee cocoa soda milk
black green chai ginger ale bitter lemon
제가 학습한 내용을 요약하여 정리한 것입니다. 내용에 오류가 있을 수 있으며, 어떠한 피드백도 감사히 받겠습니다.
감사합니다