当前位置: 首页 > news >正文

leetcode刷题日记——二叉树的锯齿形层序遍历

[ 题目描述 ]:
在这里插入图片描述
[ 思路 ]:

  • BFS,通过层次遍历,先将各层的数据存储下来,然后对偶数层的数据进行翻转,即可得到锯齿形层次遍历
  • 运行如下
    在这里插入图片描述
int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {if(!root){*returnSize=0;return NULL;}struct TreeNode* queue[2000];int** res=(int**)malloc(sizeof(int*)*2000);*returnColumnSizes = (int*)malloc(2000*sizeof(int));int front=0,rear=0;*returnSize=0;queue[rear++]=root;while(front<rear){res[*returnSize]=(int*)malloc(sizeof(int)*1024);int count=rear-front;for(int i=0;i<count;i++){res[*returnSize][i]=queue[front]->val;if(queue[front]->left) queue[rear++]=queue[front]->left;if(queue[front]->right) queue[rear++]=queue[front]->right;front++;}(*returnColumnSizes)[*returnSize]=count;(*returnSize)++;}for(int i=0;i<*returnSize;i++){if(i%2!=0){for(int j=0;j<(*returnColumnSizes)[i]/2;j++){int temp=res[i][j];res[i][j]=res[i][(*returnColumnSizes)[i]-j-1];res[i][(*returnColumnSizes)[i]-j-1]=temp;}}}return res;
}

[ 官方题解 ]:

  • BFS + 双端队列,通过双端队列,来模拟锯齿形遍历
http://www.dtcms.com/a/231641.html

相关文章:

  • 为UE5的Actor添加能够读写姿态的功能
  • stm32——UART和USART
  • 开源模型应用落地-OpenAI Agents SDK-集成Qwen3-8B-function_tool(二)
  • AI在网络安全领域的应用现状和实践
  • 虚拟机无法开启-关掉虚拟化
  • Java直接内存(directMemory)分配与查看
  • 腾讯位置商业授权AOI边界查询开发指南
  • Web攻防-SQL注入高权限判定跨库查询文件读写DNS带外SecurePriv开关绕过
  • 【Windows开发】Windows 事件跟踪 (ETW)
  • idea相关功能
  • leetcode删除排序链表中的重复元素-小白初学简单解说
  • [Java 基础]银行账户程序
  • 【无标题】Statement对象详解
  • 【Win32 API】 lstrlenA()
  • java.sql.BatchUpdateException: Incorrect string value: ‘\xF0\x9F\x91\x91**...‘
  • ROS中的里程计与IMU的消息类型解读
  • Python 类型注释 - typing
  • 如何确定微服务的粒度与边界
  • C++抽象类与多态实战解析
  • 算法训练第八天
  • Vue Router 导航方法完全指南
  • 【使用 Loki + Promtail + Grafana 搭建轻量级容器日志分析平台】
  • dxf、dwg中文字矩阵变换
  • 安装 Nginx
  • QT链接其他项目的C++文件报链接错误
  • sifli 52 反馈standby待机rc10k 15秒校准起来后,底电流会变大
  • 交叉熵的意义
  • Linux-linux和windows创建新进程的区别以及posix_spawn
  • 04.两数之和
  • 数据库同步是什么意思?数据库架构有哪些?