Open OceanApart opened 3 years ago
/**
* 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 [];
let resultList = []
let stepList = []
stepList.push(root)
function loop (stepList) {
let newStepList = []
let valList = []
for (const item of stepList) {
if (item.left) {
newStepList.push(item.left)
}
if (item.right) {
newStepList.push(item.right)
}
valList.push(item.val)
}
resultList.push(valList)
if (newStepList.length > 0) {
loop(newStepList)
}
}
loop(stepList)
return resultList
};
/**
* 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) {
var queue = [ root ]
var res = []
// 空树
if (!root) return res
// 队列不为空
while (queue.length !== 0) {
var levelResult = []
var node
let count = queue.length
while (count--) {
node = queue.shift()
levelResult.push(node.val)
// 左右节点放到下一层队列
if (node.left !== null) queue.push(node.left)
if (node.right !== null) queue.push(node.right)
}
// 当前层结果
res.push(levelResult)
}
return res
};
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/