-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.swift
64 lines (54 loc) · 1.66 KB
/
main.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// main.swift
// tree_traversal
//
// Created by Chaewan Park on 2020/01/29.
// Copyright © 2020 Chaewan Park. All rights reserved.
//
import Foundation
indirect enum Tree<T> {
case node(Tree<T>, T, Tree<T>)
case empty
}
extension Tree {
var preorder: String {
if case let .node(left, value, right) = self {
return "\(value)\(left.preorder)\(right.preorder)"
} else {
return ""
}
}
var inorder: String {
if case let .node(left, value, right) = self {
return "\(left.inorder)\(value)\(right.inorder)"
}
return ""
}
var postorder: String {
if case let .node(left, value, right) = self {
return "\(left.postorder)\(right.postorder)\(value)"
} else {
return ""
}
}
}
var nodeDictionary = Dictionary<String, [String]>()
func constructDictionary() {
let numOfNode = Int(readLine()!)!
let subTrees = (0..<numOfNode).map { _ in readLine()! }.map { (subTree) -> (String, [String]) in
let subStrings = subTree.split(separator: " ")
return (String(subStrings[0]), [String(subStrings[1]), String(subStrings[2])])
}
nodeDictionary = Dictionary(uniqueKeysWithValues: subTrees)
}
func constructTree(with value: String) -> Tree<String> {
let node = nodeDictionary[value]!
let left = node[0] == "." ? Tree.empty : constructTree(with: node[0])
let right = node[1] == "." ? Tree.empty : constructTree(with: node[1])
return Tree.node(left, value, right)
}
constructDictionary()
let tree = constructTree(with: "A")
print(tree.preorder)
print(tree.inorder)
print(tree.postorder)