|
| 1 | +// function nodeDepths(root, depth = 0) { |
| 2 | +// if (root === null) return 0; |
| 3 | +// return ( |
| 4 | +// depth + nodeDepths(root.left, depth + 1) + nodeDepths(root.right, depth + 1) |
| 5 | +// ); |
| 6 | +// } |
| 7 | + |
| 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); |
| 29 | +root.left.left = new BinaryTree(4); |
| 30 | +root.left.left.left = new BinaryTree(8); |
| 31 | +root.left.left.right = new BinaryTree(9); |
| 32 | +root.left.right = new BinaryTree(5); |
| 33 | +root.right = new BinaryTree(3); |
| 34 | +root.right.left = new BinaryTree(6); |
| 35 | +root.right.right = new BinaryTree(7); |
| 36 | + |
| 37 | +console.log(nodeDepths(root)); |
0 commit comments