当前位置: 首页 > 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 + 双端队列,通过双端队列,来模拟锯齿形遍历

相关文章:

  • 为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++抽象类与多态实战解析
  • 算法训练第八天
  • 校园网站建设提升/论坛推广网站
  • 温州市城乡建设建档案馆网站/晋江友情链接是什么意思
  • 招聘网站系统怎么做/app平台搭建
  • 网站建设案例市场/百度移动端排名
  • 网站后台密码怎么修改/海外aso优化
  • 长沙网站建设有限公司/网站搜索引擎优化技术