【问题标题】:Print binary tree recursive function打印二叉树递归函数
【发布时间】:2019-09-09 15:16:58
【问题描述】:

我正在尝试返回一个表示二叉树的数组数组。我创建了一个输出数组,其中填充了空字符串数组,其中每个数组代表树的一个级别,字符串代表该级别上每个可能的节点位置。出于某种原因,看起来我的递归函数正在更改我的父输出数组中的所有数组,而不仅仅是适当的。

var printTree = function(root) {
//first find depth of tree
    let depth = 0
    const findDepth = (node, level) => {
        depth = Math.max(depth, level);
        if (node.left) {
            findDepth(node.left, level + 1)
        }
        if (node.right) {
            findDepth(node.right, level + 1)
        }
    }
    findDepth(root, 1);
    let width = 1 + ((depth - 1) * 2)
//create array of arrays filled with blanks that match height and width
// of given tree
    let output = new Array(depth).fill(new Array(width).fill(''));
    let mid = Math.floor(width / 2);
//do DFS through tree and change output array based on position in tree
    const populate = (node, level, hori) => {
        output[level][hori] = node.val;
        if (node.left) {
            populate(node.left, level + 1, hori - 1);
        }
        if (node.right) {
            populate(node.right, level + 1, hori + 1);
        }
    }
    populate(root, 0, mid);
    return output;
};

如果我放入一棵二叉树,其根节点的 val 为 1,而它唯一的子节点的 val 为 2。

我的输出数组应该是:

[['', 1 , ''],
[2 , '' , '']]

但它看起来像这样:

[[2, 1, ''],
[2, 1, '']]

我已经在控制台记录了递归调用,但我无法弄清楚为什么这些更改会在我的矩阵的所有行中进行,而不仅仅是在适当的级别。

我该如何解决这个问题?

【问题讨论】:

  • 看起来,您使用相同的对象引用而不是更深层次的新数组。请在问题和想要的输出中添加一些输入。

标签: javascript binary-tree


【解决方案1】:

你需要改变这一行

let output = new Array(depth).fill(new Array(width).fill(''));
//                                 ^^^^^^^^^^^^^^^^^^^^^^^^^ same array!

进入

let output = Array.from({ length: depth }, _ => Array.from({ length: width }).fill(''));

因为你用相同的数组填充数组。下划线部分填充相同的数组,一个常量值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    相关资源
    最近更新 更多