【发布时间】: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, '']]
我已经在控制台记录了递归调用,但我无法弄清楚为什么这些更改会在我的矩阵的所有行中进行,而不仅仅是在适当的级别。
我该如何解决这个问题?
【问题讨论】:
-
看起来,您使用相同的对象引用而不是更深层次的新数组。请在问题和想要的输出中添加一些输入。