從上到下按層列印二叉樹,同一層結點從左至右輸出,每一層輸出一行,
分析:首先先把根節點放入要列印的佇列中,在列印之前把其子節點保存在佇列中,
這里需要有一個list存放當前層的節點,有個計數器記還有多少節點要列印,下一層由多少節點,
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function Print(pRoot) { // write code here const queue=[],res=[] if(pRoot===null){ return res } queue.push(pRoot) let nextLevel=0//下一層節點的個數 let toBePrinted=1//這一層還有多少節點要列印 let list=[]//存放每一層的節點 while(queue.length){ const pNode=queue.shift() list.push(pNode.val) if(pNode.left!==null){ queue.push(pNode.left) nextLevel++ } if(pNode.right!==null){ queue.push(pNode.right) nextLevel++ } toBePrinted-- if(toBePrinted==0){ res.push(list) list=[] toBePrinted=nextLevel nextLevel=0 } } return res }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/24676.html
標籤:其他
上一篇:樹---按之字形列印二叉樹
下一篇:面試之HTTP協議相關的問題
