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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
var levelOrder = function (root) { const ret = [] if(!root) return ret
const q = [[root,0]] while(q.length){ const [cur,depth] = q.shift() if(!ret[depth]) ret[depth] = [cur.val] else ret[depth].push(cur.val)
if(cur.left) q.push([cur.left,depth+1]) if(cur.right) q.push([cur.right,depth+1]) } return ret };
var levelOrder = function (root) { const ret = [] if (!root) return ret
const q = [root] while (q.length) { let len = q.length ret.push([]) for (let i = 0; i < len; i++) { const cur = q.shift() ret[ret.length-1].push(cur.val) if (cur.left) q.push(cur.left) if (cur.right) q.push(cur.right) } }
return ret };
var levelOrder = function (root) { const ret = [] if (!root) return ret dfs(root,0) return ret
function dfs(root,depth){ if(root === null) return
if(ret[depth]) ret[depth].push(root.val) else ret[depth] = [root.val] dfs(root.left,depth+1) dfs(root.right,depth+1) } };
|