题目地址:链接
思路: 使用队列完成层序遍历(广度优先搜索)
/**
* 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) {
let ans = [];
let pians = [];
let q = [root];
let nq = [];
while(q.length) {
let node = q.shift();
if(!node) continue;
pians.push(node.val);
if(node.left) nq.push(node.left);
if(node.right)nq.push(node.right);
if(!q.length) {
q = nq;
nq = [];
ans.push(pians);
pians = [];
}
}
return ans;
};
8万+

被折叠的 条评论
为什么被折叠?



