0

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;
}
Viet
  • 6,513
  • 12
  • 42
  • 74

1 Answers1

1

Just don't do the checks? The following code should be equivalent to what you are doing:

if (current.left === null && current.right === null)
    continue;
else {
    queue.push(current.left);
    queue.push(current.right);
}

It pushes the null value when the child is null and pushes the property value otherwise.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Yeah. You're right. I've already done the check for null above. What was I thinking? – Viet Apr 21 '20 at 15:35