forked from gazolla/Kotlin-Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree.kt
63 lines (47 loc) · 1.42 KB
/
Tree.kt
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
/**
* Created by gazolla on 10/04/16.
*/
fun main() {
val tree = TreeNode("beverages")
val hotNode = TreeNode("hot")
val coldNode = TreeNode("cold")
val teaNode = TreeNode("tea")
val coffeeNode = TreeNode("coffee")
val chocolateNode = TreeNode("cocoa")
val blackTeaNode = TreeNode("black")
val greenTeaNode = TreeNode("green")
val chaiTeaNode = TreeNode("chai")
val sodaNode = TreeNode("soda")
val milkNode = TreeNode("milk")
val gingerAleNode = TreeNode("ginger ale")
val bitterLemonNode = TreeNode("bitter lemon")
tree.addChild(hotNode)
tree.addChild(coldNode)
hotNode.addChild(teaNode)
hotNode.addChild(coffeeNode)
hotNode.addChild(chocolateNode)
coldNode.addChild(sodaNode)
coldNode.addChild(milkNode)
teaNode.addChild(blackTeaNode)
teaNode.addChild(greenTeaNode)
teaNode.addChild(chaiTeaNode)
sodaNode.addChild(gingerAleNode)
sodaNode.addChild(bitterLemonNode)
println(tree)
}
class TreeNode<T>(value: T) {
var value: T = value
var parent: TreeNode<T>? = null
var children: MutableList<TreeNode<T>> = mutableListOf()
fun addChild(node: TreeNode<T>) {
children.add(node)
node.parent = this
}
override fun toString(): String {
var s = "$value"
if (children.isNotEmpty()) {
s += " {" + children.map { it.toString() } + " }"
}
return s
}
}