JSFiddle - React, Tailwind, and code Playground
by Abdul Ahmad
JavaScript
// given binary tree, print left side of it
// -
/*
{
left: a,
right: b
}
*/
const finalStructure = [];
let newChildren = [];
let currChildren = [];
const maxIterations = 999;
let iterationNum = 0;
function printLeftView(rootNode) {
console.log('*** start');
if (!rootNode) return;
finalStructure.push(rootNode);
assignChildren(rootNode, newChildren);
console.log('gonna start');
let done = false;
while (!done) {
console.log('*** iterationNum', iterationNum);
/* iterationNum++;
if (iterationNum > maxIterations) {
done = true;
return;
}
if (newChildren.length > 0) {
finalStructure.push(newChildren[0]);
}
currChildren = newChildren;
newChildren = [];
currChildren.forEach(c => assignChildren(c, newChildren)); */
}
}
function assignChildren(node, acc) {
const { left, right } = node;
if (left) acc.push(left);
if (right) acc.push(right);
}
console.clear();
printLeftView(buildBinaryTree());
console.log('*** finalStructure', finalStructure);
function buildBinaryTree() {
const node_root_1_right_2_left_3_left = { name: 'f', left: '', right: '' };
const node_root_1_right_2_left = { name: 'e', left: node_root_1_right_2_left_3_left, right: '' };
const node_root_1_left_2_right = { name: 'd', left: '', right: '' };
const node_root_1_right = { name: 'c', left: node_root_1_right_2_left, right: '' };
const node_root_1_left = { name: 'b', left: '', right: node_root_1_left_2_right };
const node_root = { name: 'a', left: node_root_1_left, right: node_root_1_right };
return node_root;
}