-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathstring_interview_Questions.html
74 lines (60 loc) · 1.59 KB
/
string_interview_Questions.html
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
<script>
function Node(data) {
this.data = data;
this.children = [];
}
class Tree {
constructor() {
this.root = null;
}
add(data, toNodeData) {
const node = new Node(data);
// console.warn(node)
// If the toNodeData arg is passed, find it. Otherwise, store null.
const parent = toNodeData ? this.findBFS(toNodeData) : null;
// Push new node to parent whose value matches toNodeData
if (parent) {
parent.children.push(node);
} else {
// If there's no parent, make this the root node
if (!this.root) this.root = node;
else return "Tried to store node as root when root already exists.";
}
}
findBFS(data) {
const queue = [this.root];
let _node = null;
// Go thru every node in BFS
this.traverseBFS((node) => {
// Return match if found
if (node.data === data) {
_node = node;
}
});
return _node;
}
traverseBFS(cb) {
const queue = [this.root];
if (cb)
while (queue.length) {
// Store current node & remove it from queue
const node = queue.shift();
cb(node);
// Push children of current node to end of queue
for (const child of node.children) {
queue.push(child);
}
}
}
}
(function test() {
let tree = new Tree();
tree.add("root");
tree.add("Node2", "Node1");
tree.add("Node3", "Node1");
console.log(tree);
tree.traverseBFS((node) => {
console.log(node);
});
})();
</script>