Created
April 17, 2024 00:23
-
-
Save beyond-code-github/c8d98e1beca30c173e00ae5c1998deb6 to your computer and use it in GitHub Desktop.
Calculate binary tree diameter in linear time - Javascript
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
"use strict"; | |
class TreeNode { | |
data; | |
left; | |
right; | |
constructor(data) { | |
this.data = data; | |
} | |
} | |
const leftRight = {0: "left", 1: "right"} | |
// const tree = [ | |
// [1], | |
// [2, 3], | |
// [n, 4, 5, 6], | |
// [ n,n, 7,8, n,n] | |
// ] | |
function makeBinaryTree (structure) { | |
let root = new TreeNode(structure.shift()[0]); | |
let parents = [root] | |
for (const row of structure) { | |
parents = row.reduce((arr, v, i) => { | |
if (v !== null) { | |
const node = new TreeNode(v); | |
parents[Math.floor(i / 2)][leftRight[i % 2]] = node; | |
arr.push(node); | |
} | |
return arr; | |
}, []) | |
} | |
return root; | |
} | |
let diameter = 0; | |
let diameterRoot = null; | |
function postorder(node) { | |
if (node === undefined) { | |
return 0; | |
} | |
const leftHeight = postorder(node.left); | |
const rightHeight = postorder(node.right); | |
const thisDiameter = leftHeight + rightHeight + 1; | |
if (thisDiameter > diameter) { | |
diameterRoot = node; | |
diameter = thisDiameter; | |
} | |
return Math.max(leftHeight, rightHeight) + 1; | |
} | |
const n = null; | |
const tree = [ | |
[1], | |
[n, 2], | |
[ 3, 4], | |
[ 5,6, n, 7] | |
] | |
const bt = makeBinaryTree(tree); | |
postorder(bt) | |
console.log(bt); | |
console.log(diameter); | |
console.log(diameterRoot); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment