题目描述
个人解法
Javascript
BFS
/*
* @lc app=leetcode.cn id=102 lang=javascript
*
* [102] 二叉树的层序遍历
*/
// @lc code=start
/**
* 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) {
const result = [];
if (root === null) {
return [];
}
const myLevelOrder = function (roots) {
const len = roots.length;
if (len === 0) {
return;
} else {
let temp = [];
let nextRoots = [];
for (let i = 0; i < len; i++) {
temp.push(roots[i].val);
roots[i].left && nextRoots.push(roots[i].left);
roots[i].right && nextRoots.push(roots[i].right);
}
result.push(temp);
myLevelOrder(nextRoots);
}
}
myLevelOrder([root]);
return result;
};
// @lc code=end
Java
其他解法
Java
Javascript
官方 BFS
var levelOrder = function(root) {
const ret = [];
if (!root) {
return ret;
}
const q = [];
q.push(root);
while (q.length !== 0) {
const currentLevelSize = q.length;
ret.push([]);
for (let i = 1; i <= currentLevelSize; ++i) {
const node = q.shift();
ret[ret.length - 1].push(node.val);
if (node.left) q.push(node.left);
if (node.right) q.push(node.right);
}
}
return ret;
};