(root)
| 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 |
| 10 | function 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 | |
| 27 | const root = new BinaryTree(1); |
| 28 | root.left = new BinaryTree(2); |
no test coverage detected