-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.js
58 lines (44 loc) · 1.07 KB
/
tree.js
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
function Node(data) {
this.data = data;
this.children = [];
}
class Tree {
constructor() {
this.root = null;
}
add(data, toNodeData) {
const node = new Node(data);
const parent = toNodeData ? this.findBFS(toNodeData) : null;
if (parent) parent.children.push(node);
else if (!this.root) this.root = node;
else return "Root already exists!";
}
findBFS(data) {
const queue= [this.root]
let _node = null
this.traverseBFS(node => {
if(Node.data == data)
_node = node
})
return _node;
}
traverseBFS(cb) {
const queue = [this.root]
if(cb)
while(queue.length){
const node = queue.shift()
cb(node)
for(const child of node.children)
queue.push(child)
}
}
}
(function test(){
let tree = new Tree();
tree.add("Node1")
tree.add("Node2", "Node1")
tree.add("Node3", "Node1")
tree.add("Node4", "Node2")
tree.add("Node5", "Node3")
tree.traverseBFS(node => console.log("Current Node: ", node))
})()