1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function Print(pRoot) { let res = []; let queue = []; let temprow = []; if(!pRoot) return res; queue.push(pRoot); let nextLevel = 0; let nowLevel = 1; while(queue.length){ const node = queue.shift(); temprow.push(node.val); nowLevel--; if(node.left) { nextLevel++; queue.push(node.left); } if(node.right) { nextLevel++; queue.push(node.right); } if(nowLevel === 0){ res.push(temprow); temprow = []; nowLevel = nextLevel; nextLevel = 0; } } return res; }
|