leetcode 103.二叉树的锯齿形层序遍历

news2024/9/21 11:00:37

1.题目要求:

给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

在这里插入图片描述
2.做题思路:由题我们可以判断,树中每到偶数层时,就会逆置,所以我们可以采用层序遍历和逆置函数的方法来解此题
3.做题步骤:
1.我们先把层序遍历所需要的队列结构,出队和入队函数写好:

//创建队列
typedef struct queue{
    struct TreeNode* value;
    struct queue* next;
}queue_t;
//入队
void push(queue_t** head,struct TreeNode* data){
    queue_t* newnode = (queue_t*)malloc(sizeof(queue_t));
    newnode->value = data;
    newnode->next = NULL;
    if(*head == NULL){
        *head = newnode;
        return;
    }
    queue_t* tail = *head;
    while(tail->next != NULL){
        tail = tail->next;
    }
    tail->next = newnode;
}
//出队
struct TreeNode* pop(queue_t** head){
    struct TreeNode* x = (*head)->value;
    (*head) = (*head)->next;
    return x;
}

2.写好逆置函数:

void reverse(int* number,int left,int right){
    while(left <= right){
        int temp = number[left];
        number[left] = number[right];
        number[right] = temp;
        left++;
        right--;
    }
}

3.写好进行层序遍历的变量:

*returnSize = 0;
    if(root == NULL){
        return NULL;
    }
    int* each_line_nodes = (int*)malloc(sizeof(int)*2000);//记录每行结点数
    int j_1 = 0;
    int* level_order_number = (int*)malloc(sizeof(int)* 2000);//层序遍历的数组
    int j_2 = 0;
    int depth = 0;//树的高度
    int count = 1;//根结点的个数
    int index = 0;//记录每层的第一个的索引
    int nextcount = 0;//下一个结点的个数
    int size = 0;//记录队列中的个数
    queue_t* quence = NULL;//设置队列

4.进行层序遍历:

//进行层序遍历
    push(&quence,root);
    size++;
    while(size != 0){
        depth++;
        for(int i = 0;i < count;i++){
            struct TreeNode* temp = pop(&quence);
            size--;
            level_order_number[j_2] = temp->val;
            j_2++;
            if(temp->left != NULL){
                push(&quence,temp->left);
                size++;
                nextcount++;
            }
            if(temp->right != NULL){
                push(&quence,temp->right);
                size++;
                nextcount++;
            }
        }
        each_line_nodes[j_1] = count;
        j_1++;
         //如果高度为偶数时,就要对数组这一次的元素进行逆置
        if(depth % 2 == 0){
            reverse(level_order_number,index,j_2 - 1);
            index += count;
        }else{
            index += count;
        }
        count = nextcount;
        nextcount = 0;
    } 

5.再创造二维数组,把值放入二维数组中:

//设立二维数组
    int** array = (int**)malloc(sizeof(int*)* depth);
    for(int i = 0;i < depth;i++){
        array[i] = (int*)malloc(sizeof(int) * each_line_nodes[i]);
    }
    int f = 0;
    for(int i = 0;i < depth;i++){
        for(int j = 0;j < each_line_nodes[i];j++){
            array[i][j] = level_order_number[f];
            f++;
        }
    }
    *returnSize = depth;
    *returnColumnSizes = (int*)malloc(sizeof(int) * (*returnSize));
    for(int i = 0;i < depth;i++){
        (*returnColumnSizes)[i] = each_line_nodes[i];
    }
    return array;

以下为全部代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
 //创建队列
typedef struct queue{
    struct TreeNode* value;
    struct queue* next;
}queue_t;
//入队
void push(queue_t** head,struct TreeNode* data){
    queue_t* newnode = (queue_t*)malloc(sizeof(queue_t));
    newnode->value = data;
    newnode->next = NULL;
    if(*head == NULL){
        *head = newnode;
        return;
    }
    queue_t* tail = *head;
    while(tail->next != NULL){
        tail = tail->next;
    }
    tail->next = newnode;
}
//出队
struct TreeNode* pop(queue_t** head){
    struct TreeNode* x = (*head)->value;
    (*head) = (*head)->next;
    return x;
}
void reverse(int* number,int left,int right){
    while(left <= right){
        int temp = number[left];
        number[left] = number[right];
        number[right] = temp;
        left++;
        right--;
    }
}
int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {
     *returnSize = 0;
    if(root == NULL){
        return NULL;
    }
    int* each_line_nodes = (int*)malloc(sizeof(int)*2000);//记录每行结点数
    int j_1 = 0;
    int* level_order_number = (int*)malloc(sizeof(int)* 2000);//层序遍历的数组
    int j_2 = 0;
    int depth = 0;//树的高度
    int count = 1;//根结点的个数
    int index = 0;//记录每层的第一个的索引
    int nextcount = 0;//下一个结点的个数
    int size = 0;//记录队列中的个数
    queue_t* quence = NULL;//设置队列
    //进行层序遍历
    push(&quence,root);
    size++;
    while(size != 0){
        depth++;
        for(int i = 0;i < count;i++){
            struct TreeNode* temp = pop(&quence);
            size--;
            level_order_number[j_2] = temp->val;
            j_2++;
            if(temp->left != NULL){
                push(&quence,temp->left);
                size++;
                nextcount++;
            }
            if(temp->right != NULL){
                push(&quence,temp->right);
                size++;
                nextcount++;
            }
        }
        each_line_nodes[j_1] = count;
        j_1++;
        //如果高度为偶数时,就要对数组这一次的元素进行逆置
        if(depth % 2 == 0){
            reverse(level_order_number,index,j_2 - 1);
            index += count;
        }else{
            index += count;
        }
        count = nextcount;
        nextcount = 0;
    } 
    //设立二维数组
    int** array = (int**)malloc(sizeof(int*)* depth);
    for(int i = 0;i < depth;i++){
        array[i] = (int*)malloc(sizeof(int) * each_line_nodes[i]);
    }
    int f = 0;
    for(int i = 0;i < depth;i++){
        for(int j = 0;j < each_line_nodes[i];j++){
            array[i][j] = level_order_number[f];
            f++;
        }
    }
    *returnSize = depth;
    *returnColumnSizes = (int*)malloc(sizeof(int) * (*returnSize));
    for(int i = 0;i < depth;i++){
        (*returnColumnSizes)[i] = each_line_nodes[i];
    }
    return array;
}

好了,这就是我的解题方法,大家如果觉得好的话,不妨给个免费的赞吧,谢谢了^ _ ^

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2039510.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

IV(电流-电压)测试和CV(电容-电压)测试

IV&#xff08;电流-电压&#xff09;测试和CV&#xff08;电容-电压&#xff09;测试是半导体参数表征中非常重要的两种测试方法。 一、IV测试&#xff08;电流-电压测试&#xff09; 1. 定义与目的 IV测试是测量半导体器件在不同电压下的电流响应&#xff0c;以评估其电学…

树莓派智能语音助手之ASR – SpeechRecognition+PocketSphinx

想要让树莓派成为智能语音助手&#xff0c;除了会“说”&#xff0c;也要会“听”。接下来&#xff0c;就要让它实现ASR&#xff08;语音识别&#xff09;功能了。 本来想用sherpa-onnx来实现离线语音识别的&#xff0c;可惜&#xff0c;我的树莓派系统太老了&#xff0c;折腾…

mybatis常见面试问题

0.原生JDBC样例: public class MainClass { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // 加载数据库驱动 Class.forName("com.mysql.cj.jdbc.Driver"); // 建立连接 String url = &q…

视觉SLAM ch3补充——在Linux中配置VScode以及CMakeLists如何添加Eigen库

ch3中的所有代码&#xff0c;除了在kdevelop中运行&#xff0c;还可以在VScode中运行。下面将简要演示配置过程&#xff0c;代码不再做解答&#xff0c;详细内容在下面的文章中。&#xff08;这一节中的pangolin由于安装过程中会出现很多问题&#xff0c;且后续内容用不到该平台…

重磅官宣!追光少年【彭禹锦】荣担任中国美育促进网amp;IPA美育中国行代言人

在美育事业蓬勃发展的今天&#xff0c;一位年仅15岁的少年以其非凡的艺术才华和积极向上的精神风貌&#xff0c;成为了万众瞩目的焦点。中国美育促进网与IPA美育中国行正式宣布&#xff0c;才华横溢、正能量满满的追光少年彭禹锦受邀担任“中国美育促进网&IPA美育中国行”代…

c++中__int128的使用

需要10^30才可以存&#xff0c;我们可以用__int128来算 #include<bits/stdc.h>using namespace std;bool is_sqr(__int128 x) {__int128 l -1, r 1e16;while (r - l > 1) {__int128 m (l r) / 2;__int128 m2 m * m;if (m2 < x) {l m;} else {r m;}}if (l *…

【机器学习】RNN循环神经网络的基本概念、工作原理(含python代码)和应用领域

引言 递归神经网络&#xff08;RNN&#xff09;是一类用于处理序列数据的神经网络。它们在处理如时间序列数据、语音、文本和其他序列格式数据时特别有用 文章目录 引言一、RNN的基本概念1.1 RNN的定义组成1.1.1 单个神经元1.1.2 网络结构 1.2 RNN的工作原理及代码示例1.2.1 循…

8月7日-8日学习

首先是昨天看到的gemma 2 中训练2B模型用了知识蒸馏&#xff0c;找了一下技术报告 结果先找到了一代的半天没有看到知识蒸馏的部分 然后在二代里面找到了 只有很小的一部分 就是用小模型学习大模型的概率预测分布 然后这里的话又找到了华为发布的小模型论文 Rethinking Optim…

Centos7安装Redis(采用docker安装方式)

文章目录 1 拉取Redis镜像2 上传并修改配置文件3 启动Docker容器4 查看Docker是否正常启动 linux系统安装redis可以自己上传程序&#xff0c;手动启动&#xff0c;也可以用docker以容器形式启动。 redis建议可采用docker安装&#xff0c;如果是例如mysql这种追求稳定的关系型数…

mmdeployv0.6 mmdetectionv2.4、mmcv-full1.6安装及环境搭建

一、安装条件 Step 1.创建conda虚拟环境并激活 conda create -n mmdeploy python3.8 -y #创建环境 conda activate mmdeploy #激活环境Step 2.安装 PyTorch #如果网不好&#xff0c;可以这样安装 pip3 install torch1.8.1cu111 torchvision0.9.1cu111 -…

基于python的百度迁徙迁入、迁出数据分析(十)

副标题&#xff1a;从百度迁徙数据看——迁徙数据特征分析 书接上文&#xff0c;我们先回顾一下我们统计的时间口径&#xff1a;2024年2月1日——2024年8月1日&#xff0c;这里包含了春运、清明、五一、端午、四个中大型国定假日&#xff0c;我们详细分析一下在当下的统计周期…

GOIP语音网关对接VOS3000技巧 落地于呼叫配置

GOIP语音网关对接VOS3000技巧 落地和呼叫以鼎信GOIP网关为例 首先登录vos端&#xff0c;添加落地网关和账户 账户添加&#xff1a; 账户管理&#xff0c;先添加账户然后应用&#xff0c;在过滤看看是否添加成功 给账户添加一个费率 双击费率数量添加费率的地区前缀&#xff0…

关于宠物浮毛对身体是否有害?宠物空气净化器选对告别浮毛困扰

说到宠物掉毛&#xff0c;大家是不是都会心里咯噔一下&#xff0c;担心这会不会对身体有啥不好&#xff1f;这确实是很多养宠人&#xff0c;还有那些正打算养宠的朋友心里的一块大石头。而且啊&#xff0c;这浮毛问题还常常成了家庭纷争的源头&#xff0c;特别是那些怀孕了的、…

【约数之和】

题目 TLE代码 #include<bits/stdc.h> using namespace std; typedef long long LL; #define x first #define y secondconst int N 5e710; const int MOD 9901; LL a, b; unordered_map<int, int> cnt; LL res 1; LL fast(int base, int expo) {LL result 1;…

TreeSet的排序方式

一.TreeSet的特点&#xff1a; 二.TreeSet对象排序练习题&#xff1a; 需求&#xff1a;利用TreeSet存储整数并进行排序 package com.itheima.a06mySet; ​ import java.util.TreeSet; ​ public class A05_TreeSetDemo1 {public static void main(String[] args) {//1.创建T…

链表算法题一

​ 旋转链表 旋转链表 首先考虑特殊情况 若给定链表为空表或者单个节点,则直接返回head,不需要旋转操作.题目给定条件范围: 0 < k < 2 ∗ 1 0 9 0 < k < 2 * 10^9 0<k<2∗109,但是受给定链表长度的限制,比如示例2中,k4与k1的效果等价. 那么可以得出kk%l…

QLabel设置图像的方法+绘制文本换行显示

1、QLabel设置图像有两种方法 (1) void setPicture(const QPicture &); (2) void setPixmap(const QPixmap &); QPicture和QPixmap都是继承于QPaintDevice&#xff0c;它们都可以通过加载图片的方式获取&#xff1a;bool load(QIODevice *dev, const char *format …

8.8网络编程

笔记 网络基础 一.网络通信的引入 IPC通信方式&#xff0c;只能完成同一台主机之间多个进程间的通信&#xff0c;在实现跨主机的多个进程间通信时&#xff0c;就显得力不从心了。所以我们引入了网络通信&#xff0c;基于套接字socket的通信方式&#xff0c;能够完成同一主机…

AI Agent工程师认证-学习笔记(2)——【多Agent】AgentScope

基础学习链接&#xff1a;【多Agent】AgentScope学习指南 速通攻略&#xff1a;零基础做个多智能体游戏 Agentscope入门文档&#xff1a;AgentScope 初探 应用开发进阶&#xff1a;AgentScope应用开发入门 AgentScope官方文档&#xff1a;AgentScope官方文档 AgentScope开…

Ghidra:开源软件逆向工程框架

Ghidra 是一个软件逆向工程 (SRE) 框架 Ghidra 是一种尖端的开源软件逆向工程 (SRE) 框架&#xff0c;是美国国家安全局 (NSA) 研究局的产品。 Ghidra 该框架具有高端软件分析工具&#xff0c;使用户能够分析跨各种平台&#xff08;包括 Windows、macOS 和 Linux&#xff09…