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

二叉树的锯齿形层次遍历

问题描述

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

例如:

给定二叉树 [3,9,20,null,null,15,7],

    3

   / \

  9  20

     /  \

   15   7

返回锯齿形层次遍历如下:

[

  [3],

  [20,9],

  [15,7]

]

程序输出:

3 20 9 15 7 

可使用以下main函数:

#include <iostream>

#include <queue>

#include <cstdlib>

#include <cstring>

using namespace std;

struct TreeNode

{

    int val;

    TreeNode *left;

    TreeNode *right;

    TreeNode() : val(0), left(NULL), right(NULL) {}

    TreeNode(int x) : val(x), left(NULL), right(NULL) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}

};

TreeNode* inputTree()

{

    int n,count=0;

    char item[100];

    cin>>n;

    if (n==0)

        return NULL;

    cin>>item;

    TreeNode* root = new TreeNode(atoi(item));

    count++;

    queue<TreeNode*> nodeQueue;

    nodeQueue.push(root);

    while (count<n)

    {

        TreeNode* node = nodeQueue.front();

        nodeQueue.pop();

        cin>>item;

        count++;

        if (strcmp(item,"null")!=0)

        {

            int leftNumber = atoi(item);

            node->left = new TreeNode(leftNumber);

            nodeQueue.push(node->left);

        }

        if (count==n)

            break;

        cin>>item;

        count++;

        if (strcmp(item,"null")!=0)

        {

            int rightNumber = atoi(item);

            node->right = new TreeNode(rightNumber);

            nodeQueue.push(node->right);

        }

    }

    return root;

}

int main()

{

    TreeNode* root;

    root=inputTree();

    vector<vector<int> > res=Solution().zigzagLevelOrder(root);

    for(int i=0; i<res.size(); i++)

    {

        vector<int> v=res[i];

        for(int j=0; j<v.size(); j++)

            cout<<v[j]<<" ";

    }

}

输入说明

首先输入结点的数目n(注意,这里的结点包括题中的null空结点)

然后输入n个结点的数据,需要填充为空的结点,输入null。

输出说明

输出结果,每个数据的后面跟一个空格。

输入范例

7
3 9 20 null null 15 7

输出范例

3 20 9 15 7 

实现思路

对树进行层次遍历,只需要多一步操作:用一个变量记录遍历的是哪一层的数据,若为偶数则要将遍历该层得到的一维数组进行reverse。

实现代码
#include <iostream>#include <queue>#include <cstdlib>#include <cstring>#include<algorithm>using namespace std;struct TreeNode{int val;TreeNode *left;TreeNode *right;TreeNode() : val(0), left(NULL), right(NULL) {}TreeNode(int x) : val(x), left(NULL), right(NULL) {}TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}};TreeNode* inputTree(){int n,count=0;char item[100];cin>>n;if (n==0)return NULL;cin>>item;TreeNode* root = new TreeNode(atoi(item));count++;queue<TreeNode*> nodeQueue;nodeQueue.push(root);while (count<n){TreeNode* node = nodeQueue.front();nodeQueue.pop();cin>>item;count++;if (strcmp(item,"null")!=0){int leftNumber = atoi(item);node->left = new TreeNode(leftNumber);nodeQueue.push(node->left);}if (count==n)break;cin>>item;count++;if (strcmp(item,"null")!=0){int rightNumber = atoi(item);node->right = new TreeNode(rightNumber);nodeQueue.push(node->right);}}return root;}class Solution{
public:vector<vector<int>> zigzagLevelOrder(TreeNode *root){vector<vector<int>> res;queue<TreeNode *>q;int i = 0;//记录是哪一层,若为偶数层则将该层数据reverseif(root!=NULL)q.push(root);while(!q.empty()){i++;int len = q.size();vector<int>tem;while(len){TreeNode *p = q.front();q.pop();tem.push_back(p->val);if(p->left) q.push(p->left);if(p->right) q.push(p->right);len--;}if(i%2==0){reverse(tem.begin(),tem.end());}res.push_back(tem);}return res;}
};int main(){TreeNode* root;root=inputTree();vector<vector<int> > res=Solution().zigzagLevelOrder(root);for(int i=0; i<res.size(); i++){vector<int> v=res[i];for(int j=0; j<v.size(); j++)cout<<v[j]<<" ";}}

http://www.lryc.cn/news/608957.html

相关文章:

  • 9.苹果ios逆向-FridaHook-ios中的算法(CCCrypt)
  • CCF-GESP 等级考试 2025年6月认证C++一级真题解析
  • wordpress登陆前登陆后显示不同的顶部菜单
  • 最简单的零基础软件测试学习路线
  • Libevent(5)之使用教程(4)工具
  • k8s黑马教程笔记
  • 快速搭建一个非生产k8s环境
  • 【运维基础】Linux 硬盘分区管理
  • k8s+isulad 国产化技术栈云原生技术栈搭建4-添加worker节点
  • Hyper-V + Centos stream 9 搭建K8s集群(二)
  • k8s+isulad 国产化技术栈云原生技术栈搭建3-master节点安装
  • [硬件电路-148]:数字电路 - 什么是CMOS电平、TTL电平?还有哪些其他电平标准?发展历史?
  • Go语言实战案例:TCP服务器与客户端通信
  • 案例介绍|JSON数据格式的转换|pyecharts模块简介
  • Kafka——怎么重设消费者组位移?
  • 构建企业级Web应用:AWS全栈架构深度解析
  • AtCoder Beginner Contest 417
  • [硬件电路-147]:模拟电路 - DC/DC电压的三种架构:升压(Boost)、降压(Buck)或升降压(Buck-Boost)
  • 跨语言模型中的翻译任务:XLM-RoBERTa在翻译任务中的应用
  • 界面规范4-按钮
  • IntelliJ IDEA开发编辑器摸鱼看股票数据
  • Parcel 使用详解:零配置的前端打包工具
  • 关于车位引导及汽车乘梯解决方案的专业性、系统性、可落地性强的综合设计方案与技术实现说明,旨在为现代智慧停车楼提供高效、安全、智能的停车体验。
  • electron-多线程
  • 嵌入式——数据结构:单向链表的函数创建
  • 常见的深度学习模块/操作中的维度约定(系统性总结)
  • Docker-03.快速入门-部署MySQL
  • 介绍JAVA语言、介绍greenfoot 工具
  • 北邮:LLM强化学习架构Graph-R1
  • 【机器学习】线性回归算法详解:线性回归、岭回归、Lasso回归与Elastic Net