按级别顺序遍历时,显示不平衡二叉树的空同级兄弟

问题描述 投票:0回答:1

也许是重复或奇怪的问题,但我无法在任何地方找到答案:

我想以不平衡二叉树]的广度优先搜索顺序打印路径,并带有空同级。我的代码有效,并且我尝试改进它,但是有点卡住了。我只是想知道是否还有一种更聪明的方法来代替多次检查。

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;
}

也许是重复的问题或奇怪的问题,但我无法在任何地方找到答案:我想以不平衡的二叉树和同级的空值打印广度优先搜索顺序中的路径。我的...

javascript binary-tree breadth-first-search
1个回答
1
投票

只是不做检查?以下代码应等同于您的工作:

© www.soinside.com 2019 - 2024. All rights reserved.