[英]Print binary tree recursive function
我试图返回一个表示二叉树的数组数组。 我创建了一个填充了空字符串数组的输出数组,其中每个数组代表树的一个级别,字符串代表该级别上每个可能的节点位置。 出于某种原因,看起来我的递归函数正在对父输出数组中的所有数组进行更改,而不仅仅是对适当的数组进行更改。
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, '']]
我已经控制台记录了递归调用,但我无法弄清楚为什么在矩阵的所有行中进行这些更改,而不仅仅是在适当的级别进行更改。
我该如何解决这个问题?
你需要改变这一行
let output = new Array(depth).fill(new Array(width).fill(''));
// ^^^^^^^^^^^^^^^^^^^^^^^^^ same array!
进入
let output = Array.from({ length: depth }, _ => Array.from({ length: width }).fill(''));
因为你用相同的数组填充数组。 下划线部分填充相同的数组,一个常量值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.