I've looked at other answers on here, but everything is either is messily written, or the code doesn't operate the same as mine does. All I am looking for is a crystal clear explanation as to why the time complexity of this breadth first search depicted below is O(v + e).
class Node {
constructor(name) {
this.name = name;
this.children = [];
}
breadthFirstSearch() {
const array = []
const queue = [this]
while(queue.length) {
const node = queue.shift()
array.push(node.name)
queue.push(...node.children)
}
return array
}
}
Each of the vertexes below are each of the Node class depicted above. You can imagine the breadthFirstSearch
method being called by the "A" node.
A
/ | \
B C D
/ \ / \
E F G H
/ \
I J
I understand the O(v) part, because its pretty clear that we visit every node. The O(e) part is the one I cannot wrap my head around. Thanks in advance.