-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathTree.ts
80 lines (66 loc) · 1.68 KB
/
Tree.ts
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
65
66
67
68
69
70
71
72
73
74
75
76
77
import { Queue } from '../Queue'
import { Stack } from '../Stack'
export class Node {
public data: any
public children: Node[] = []
public parent: Node
constructor (data: any, parent: Node = null) {
this.data = this.data
this.parent = parent
}
public appendChild (data: any): Node {
const node = new Node(this, data)
this.children.push(node)
return node
}
public appendNode (node: Node) {
node.parent = this
this.children.push(node)
}
public removeNode (node: Node) {
const index = this.children.indexOf(node)
if (index !== -1) {
this.children.splice(index, 1)
}
}
public DFSWalk (callBack: Function) {
const stack = new Stack<any>()
let current: Node = this
stack.push(current)
while (stack.sizeOf() !== 0) {
current = stack.pop()
callBack(current)
for (let item of current.children) {
stack.push(item)
}
}
}
public BFSWalk (callBack: Function) {
const queue = new Queue<any>()
let current: Node = this
queue.enQueue(current)
while (queue.sizeOf() !== 0) {
current = queue.deQueue()
callBack(current)
for (let node of current.children) {
queue.enQueue(node)
}
}
}
public colorDFSWalk (callBack: Function) {
const stack = new Stack<any>()
let current: Node = this
const color = []
while (current || stack.sizeOf() > 0) {
if (current) {
if (color[current.data] !== 'black') {
stack.push(current)
}
current = current.children.find(n => n && color[n.data] !== 'black')
} else {
current = stack.pop()
color[current.data] = 'black'
}
}
}
}