Maybe a duplicate or odd question but I haven't been able to find the answer anywhere:
I want to print out the path in Breadth-First Search order of an unbalanced binary tree with null siblings. My code works and I've tried to improve it but I'm a bit stuck. I just wonder if there's a more clever way of doing it instead of multiple checks.
function traverse(tree) {
const path = [];
let queue = [tree];
while (queue.length > 0) {
const current = queue.shift();
if (current !== null) path.push(current.val);
else {
path.push(null);
continue;
}
if (current.left === null && current.right === null) continue;
else if (current.left !== null && current.right === null) {
queue.push(current.left);
queue.push(null);
}
else if (current.left === null && current.right !== null) {
queue.push(null);
queue.push(current.right);
}
else {
queue.push(current.left);
queue.push(current.right);
}
}
return path;
}