Created
November 17, 2021 06:46
-
-
Save cagataycali/156a3b9ad0453cb6f788dc1afa083bf3 to your computer and use it in GitHub Desktop.
[BinaryTree] Node depths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require("assert"); | |
// O(n) time | O(h) space - h is height. | |
function nodeDepths(root, depth = 0) { | |
if (root === null) { | |
return 0; | |
} | |
return depth + nodeDepths(root.left, depth + 1) + nodeDepths(root.right, depth + 1); | |
} | |
// This is the class of the input binary tree. | |
class BinaryTree { | |
constructor(value) { | |
this.value = value; | |
this.left = null; | |
this.right = null; | |
} | |
} | |
const root = new BinaryTree(1); | |
root.left = new BinaryTree(2); | |
root.left.left = new BinaryTree(4); | |
root.left.left.left = new BinaryTree(8); | |
root.left.left.right = new BinaryTree(9); | |
root.left.right = new BinaryTree(5); | |
root.right = new BinaryTree(3); | |
root.right.left = new BinaryTree(6); | |
root.right.right = new BinaryTree(7); | |
const actual = nodeDepths(root); | |
assert.deepStrictEqual(actual, 16); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment