MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / nodeDepths

Function nodeDepths

binary-trees/node-depths.js:10–25  ·  view source on GitHub ↗
(root)

Source from the content-addressed store, hash-verified

8// O(n) time where n is the number of nodes
9// O(h) space where h is the height of the tree, because at most we are storing h items on the stack
10function nodeDepths(root) {
11 let sum = 0;
12 const stack = [{ node: root, depth: 0 }];
13
14 //DFS
15 while (stack.length > 0) {
16 const currentNode = stack.pop();
17 const { node, depth } = currentNode;
18
19 if (node === null) continue;
20 sum += depth;
21 stack.push({ node: node.left, depth: depth + 1 });
22 stack.push({ node: node.right, depth: depth + 1 });
23 }
24 return sum;
25}
26
27const root = new BinaryTree(1);
28root.left = new BinaryTree(2);

Callers 1

node-depths.jsFile · 0.85

Calls 2

popMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected