优先广度优先遍历
遍历过程中,记录每个每个节点的层级,并将其添加到不同的数组中去
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
if(!root) return [];
const q = [[root, 0]];
const res = [];
while(q.length) {
const [n, level] = q.shift();
if(!res[level]) {
res[level] = [n.val];
} else {
res[level].push(n.val);
}
if(n.left) q.push([n.left, level + 1]);
if(n.right) q.push([n.right, level + 1]);
}
return res;
};
优化空间:将队列中属于同一层级的数据,一次性的添加到数组中。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
if(!root) return [];
const q = [root];
const res = [];
while(q.length) {
res.push([])
let length = q.length;
while(length--) {
const n = q.shift();
res[res.length-1].push(n.val)
if(n.left) q.push(n.left);
if(n.right) q.push(n.right);
}
}
return res;
};