algorighm/top-interview-leetcode150/binary-tree/103二叉树的锯齿形层次bianli.js

52 lines
1.6 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[][]}
* https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/?envType=study-plan-v2&envId=top-interview-150
*/
const zigzagLevelOrder = function (root) {
};
/*
这个题目就是102的变种只需记录一个遍历order如果order为true就从左到右否则从右到左这里直接复制102的代码
*/
function f1(root) {
if (!root) return []; // 如果树为空,返回空数组
const result = []; // 用于存储每一层的节点值
const queue = [root]; // 初始化队列,开始时只有根节点
let order = true; // 判断这一层数据是从左到右还是从右到左
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(order ? levelValues : levelSize.reverse());
order = !order;
}
return result;
}