[英]Print binary tree recursive function
I'm attempting to return an array of arrays that represents a binary tree.我试图返回一个表示二叉树的数组数组。 I created an output array filled with arrays of empty strings, where each array represents one level of the tree and the strings represent each possible node position on that level.
我创建了一个填充了空字符串数组的输出数组,其中每个数组代表树的一个级别,字符串代表该级别上每个可能的节点位置。 For some reason, it looks like my recursive function is making changes to all arrays in my parent output array, rather than just the appropriate one.
出于某种原因,看起来我的递归函数正在对父输出数组中的所有数组进行更改,而不仅仅是对适当的数组进行更改。
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;
};
If I put in a binary tree with a root node with the val of 1, and its only child is left with a val of 2.如果我放入一棵二叉树,其根节点的 val 为 1,其唯一的子节点的 val 为 2。
My output array should be:我的输出数组应该是:
[['', 1 , ''],
[2 , '' , '']]
But instead it looks like this:但它看起来像这样:
[[2, 1, ''],
[2, 1, '']]
I have console logged the recursive calls and I can't figure out why these changes are being made in all rows of my matrix and not just at the appropriate level.我已经控制台记录了递归调用,但我无法弄清楚为什么在矩阵的所有行中进行这些更改,而不仅仅是在适当的级别进行更改。
How do I solve this problem?我该如何解决这个问题?
You need to change this line你需要改变这一行
let output = new Array(depth).fill(new Array(width).fill(''));
// ^^^^^^^^^^^^^^^^^^^^^^^^^ same array!
into进入
let output = Array.from({ length: depth }, _ => Array.from({ length: width }).fill(''));
because you fill the array with the same array.因为你用相同的数组填充数组。 The underlined part fills with the same array, a constant value.
下划线部分填充相同的数组,一个常量值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.