Skip to content

Commit ceb1971

Browse files
committed
add node depths question
1 parent fa19016 commit ceb1971

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

binary-trees/node-depths.js

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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

Comments
 (0)