Skip to content

Commit 96e5aef

Browse files
committed
update binary tree diameter
1 parent 6c5274a commit 96e5aef

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

binary-trees/Binary-Tree-Diameter.js

+16-12
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
// Time O(n) - where n is the number of nodes
2+
// Space O(h) - average case when the tree is balanced
3+
// Space O(n) - worst case
14

2-
/////////////////////////////////////////////////////////////////////////////////////
3-
// Binary Tree Diamaeter
4-
5+
// This is an input class. Do not edit.
56
class BinaryTree {
67
constructor(value) {
78
this.value = value;
@@ -11,28 +12,32 @@ class BinaryTree {
1112
}
1213

1314
class TreeInfo {
14-
constructor(diameter, height) {
15+
constructor(diameter, heigth) {
1516
this.diameter = diameter;
16-
this.height = height;
17+
this.height = heigth;
1718
}
1819
}
1920

2021
function binaryTreeDiameter(tree) {
21-
return getTreeInfo(tree).diameter;
22+
return getTreeInfoHelper(tree).diameter;
2223
}
2324

24-
function getTreeInfo(tree) {
25+
function getTreeInfoHelper(tree) {
2526
if (tree === null) return new TreeInfo(0, 0);
2627

27-
const leftTreeInfo = getTreeInfo(tree.left);
28-
const rightTreeInfo = getTreeInfo(tree.right);
28+
const leftTreeInfo = getTreeInfoHelper(tree.left);
29+
const rightTreeInfo = getTreeInfoHelper(tree.right);
2930

30-
const longestPathTroughRoot = leftTreeInfo.height + rightTreeInfo.height;
31+
// maxDiameterSoFar = max(leftNode.diameter and right.diameter);
32+
// largestPossiblePath = left.height + right.height
33+
// currentDiameter = max (longestPossiblePath and maxDiameterSoFar)
34+
// currentHeight = 1 + max (left.height, right.height);
3135
const maxDiameterSoFar = Math.max(
3236
leftTreeInfo.diameter,
3337
rightTreeInfo.diameter
3438
);
35-
const currentDiameter = Math.max(longestPathTroughRoot, maxDiameterSoFar);
39+
const largestPossiblePath = leftTreeInfo.height + rightTreeInfo.height;
40+
const currentDiameter = Math.max(maxDiameterSoFar, largestPossiblePath);
3641
const currentHeight = 1 + Math.max(leftTreeInfo.height, rightTreeInfo.height);
3742

3843
return new TreeInfo(currentDiameter, currentHeight);
@@ -49,4 +54,3 @@ root.left.right.right.right = new BinaryTree(6);
4954
root.right = new BinaryTree(2);
5055

5156
console.log(binaryTreeDiameter(root));
52-

0 commit comments

Comments
 (0)