我試圖返回代表二叉樹的數(shù)組的數(shù)組。我創(chuàng)建了一個(gè)輸出數(shù)組,其中填充了空字符串?dāng)?shù)組,其中每個(gè)數(shù)組代表樹的一個(gè)級(jí)別,字符串代表該級(jí)別上每個(gè)可能的節(jié)點(diǎn)位置。出于某種原因,看來(lái)我的遞歸函數(shù)正在更改父輸出數(shù)組中的所有數(shù)組,而不僅僅是適當(dāng)?shù)臄?shù)組。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;};如果我將二叉樹的根節(jié)點(diǎn)的val設(shè)置為1,則其唯一的子節(jié)點(diǎn)的val設(shè)置為2。我的輸出數(shù)組應(yīng)該是:[['', 1 , ''],[2 , '' , '']]但是相反,它看起來(lái)像這樣:[[2, 1, ''],[2, 1, '']]我已經(jīng)在控制臺(tái)上記錄了遞歸調(diào)用,但我無(wú)法弄清楚為什么這些變化是在矩陣的所有行中進(jìn)行的,而不僅僅是在適當(dāng)?shù)募?jí)別上進(jìn)行的。我該如何解決這個(gè)問(wèn)題?
打印二叉樹遞歸函數(shù)
紅顏莎娜
2021-05-03 13:53:26