[英]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.