给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
解题思路
层序遍历顺序就是广度优先遍历。
在遍历的时候需要记录当前节点所处的层级,方便将其添加到不同的数组中。
解题步骤
广度优先遍历二叉树。
遍历过程中,记录每个节点的层级,并将其添加到不同的数组中。
1、
/**
* 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 res = []
const q = [[root, 0]]
while (q.length) {
const [n, level] = q.shift()
res[level] ? res[level].push(n.val) : res.push([n.val])
if (n.left) q.push([n.left, level + 1])
if (n.right) q.push([n.right, level + 1])
}
return res
};
2、
/**
* 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 res = []
if (!root) {
return res
}
// 声明队列用于存储后续数据
const queue = []
queue.push(root)
// 遍历队列
while(queue.length) {
// 针对本轮操作,创建一个新的二维数组
res.push([])
const len = queue.length
for(let i = 0; i < len; i++) {
// 将本次操作的节点出队
const node = queue.shift()
res[res.length-1].push(node.val)
// 检测是否存在左右子节点,如果有,就入队
if (node.left) {
queue.push(node.left)
}
if (node.right) {
queue.push(node.right)
}
}
}
return res
};
1
1345

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



