algorighm/top-interview-leetcode150/binary-tree/102二叉树的层序遍历.js

75 lines
2.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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[][]}
*/
const levelOrder = function (root) {
};
/*
层序遍历,无需多言
*/
function f1(root) {
if (!root) return []; // 如果树为空,返回空数组
const result = []; // 用于存储每一层的节点值
const queue = [root]; // 初始化队列,开始时只有根节点
while (queue.length > 0) {
const levelSize = queue.length; // 当前层的节点数
const levelValues = []; // 存储当前层节点的值
// 遍历当前层的所有节点
for (let i = 0; i < levelSize; i++) {
const node = queue.shift(); // 弹出队列中的第一个节点
levelValues.push(node.val); // 将节点值加入当前层的结果
// 如果节点有左子节点,加入队列
if (node.left) queue.push(node.left);
// 如果节点有右子节点,加入队列
if (node.right) queue.push(node.right);
}
// 将当前层的节点值加入最终结果
result.push(levelValues);
}
return result;
}
/*
二叉树的层序遍历老生常谈了通常使用一个队列来处理但是js中的数组shift的操作复杂度为O(1)这里我们使用一个head指针来优化表示
shift要弹出的元素
*/
function f2(root) {
const ans = []; // 返回的遍历结果
const queue = []; // 层序遍历使用的队列
if (root) queue.push(root);
let head = 0; // 队列需要弹出的元素的下标
while (head < queue.length) {
const n = queue.length - head; // 每一层的元素个数
// 遍历这一层元素将值存入levelDatas中
const levelDatas = [];
for (let i = 0; i < n; i++) {
const node = queue[head++];
levelDatas.push(node.val);
// 将左右节点加入下一层
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return ans;
}