binary-tree-no-recursion
by Abdul Ahmad
JavaScript
// given binary tree, print left side of it
// -
/*
{
left: a,
right: b
}
*/
const finalStructure = [];
let newChildren = [];
let currChildren = [];
const maxIterations = 9999;
let iterationNum = 0;
function printLeftView(rootNode) {
if (!rootNode) return;
finalStructure.push(rootNode);
assignChildren(rootNode, newChildren);
let done = false;
while (!done || iterationNum < maxIterations) {
iterationNum++;
if (newChildren.length > 0) {
finalStructure.push(newChildren[0]);
} else {
break;
}
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;
}