Skip to content

Instantly share code, notes, and snippets.

@beyond-code-github
Created April 17, 2024 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beyond-code-github/2a4838e885ec4776394aabb26074ea4f to your computer and use it in GitHub Desktop.
Save beyond-code-github/2a4838e885ec4776394aabb26074ea4f to your computer and use it in GitHub Desktop.
Initialise a simple binary tree in a terse way - Javascript
"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;
}
const n = null;
const tree = [
[1],
[2, 3],
[n, 4, 5, 6],
[ n,n, 7,8, n,n]
]
console.log(makeBinaryTree(tree))
// TreeNode {
// data: 1,
// left: TreeNode {
// data: 2,
// left: undefined,
// right: TreeNode { data: 4, left: undefined, right: undefined }
// },
// right: TreeNode {
// data: 3,
// left: TreeNode { data: 5, left: [TreeNode], right: [TreeNode] },
// right: TreeNode { data: 6, left: undefined, right: undefined }
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment