/**
* 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 res = []
let queue = [root]
let count = 0 // 记录当前层级
while(queue.length){
console.log("queue",queue)
res[count] = [] // 初始化当前层级
let countNum = queue.length // 当前层级的节点数
while(countNum--){ // 遍历当前层级的节点数
let node = queue.shift() // 从前开始取当前层级的节点
res[count].push(node.val) // 推入每层的节点值
node.left && queue.push(node.left) // 将当前层级的节点的左右节点推入栈中,供下一层级遍历
node.right && queue.push(node.right)// 将当前层级的节点的左右节点推入栈中,供下一层级遍历
}
count++ // 层级+1
}
return res
};
基本逻辑:
层序遍历使用的时广度优先遍历,使用队列存取,先进先出,与广度优先遍历不同的是,广度优先遍历返回一个一维数组,不分层级,层序遍历分层级,返回多维数组,在每次遍历的过程中,把整层节点都处理完之后,再处理下一层
1. 将每一层的节点 push 进队列里
2. 对队列中所有节点获取其值,作为返回数组对应层级的值
3. 最终返回一个多维数组,每一维度代表一层,由高到低
参考:
https://blog.csdn.net/m0_52409770/article/details/123225716
https://blog.csdn.net/weixin_45771601/article/details/126215915
https://leetcode.cn/problems/binary-tree-level-order-traversal/solution/bfs-de-shi-yong-chang-jing-zong-jie-ceng-xu-bian-l/