第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

打印二叉樹遞歸函數(shù)

打印二叉樹遞歸函數(shù)

紅顏莎娜 2021-05-03 13:53:26
我試圖返回代表二叉樹的數(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)題?
查看完整描述

1 回答

?
慕慕森

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊

您需要更改此行


let output = new Array(depth).fill(new Array(width).fill(''));

//                                 ^^^^^^^^^^^^^^^^^^^^^^^^^ same array!

進(jìn)入


let output = Array.from({ length: depth }, _ => Array.from({ length: width }).fill(''));

因?yàn)槟孟嗤臄?shù)組填充了數(shù)組。帶下劃線的部分用相同的數(shù)組填充,為常數(shù)。


查看完整回答
反對(duì) 回復(fù) 2021-05-06
  • 1 回答
  • 0 關(guān)注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)