二叉树的遍历C语言

二叉树作为FDS课程最核心的数据结构之一,要求每个人都掌握!

这是一道简单的二叉树问题!

我们将给出一颗二叉树,请你输出它的三种遍历,分别是先序遍历,中序遍历,后序遍历!

输入格式 :

二叉树将以这样的形式给出:

第一行给出一个正整数N(N<=100),表示二叉树上的节点个数!

接下来N行,每行包含三个整数,i,l,r,分别代表第i个节点的左右孩子!

如果它的左/右孩子为空,则在对应位置给出-1!

题目保证1是根节点!

输出格式 :

请你输出它的三种遍历!

第一行输出先序遍历,第二行输出中序遍历,第三行输出后序遍历!

每行末尾无多余空格!

输入样例 :

在这里给出一组输入。例如:

3

1 2 3

2 -1 -1

3 -1 -1

输出样例 :

在这里给出相应的输出。例如:

1 2 3

2 1 3

2 3 1

c 复制代码
#include <stdio.h>
#include <stdlib.h>

typedef int Elementyple;
typedef struct TNode* BiTree;
typedef struct TNode{
    Elementyple Data;
    struct TNode* Left;
    struct TNode* Right;
}tnode;

int N;

BiTree createNode() {
   BiTree node = new TNode;
    node->Left = NULL;
    node->Right = NULL;
    return node;
}

BiTree CreaTree(int number[10000][15],int x){
	if(x==-1)
	return NULL;
     BiTree BT;
    // BT=(BiTree)malloc(sizeof(struct TNode));
    BT=createNode();
     BT->Data=x;
     BT->Left=CreaTree(number,number[x][0]);
     BT->Right=CreaTree(number,number[x][1]);
     return BT;
}
int flag=0;

void PreorderTraversal( BiTree BT ){
    if(BT){
	    flag++;
	    if(flag==N)
	    printf("%d",BT->Data);
		else 
        printf("%d ",BT->Data);
        PreorderTraversal(BT->Left);
        PreorderTraversal(BT->Right);
    }
}
void InorderTraversal( BiTree BT){
    if(BT){
        InorderTraversal(BT->Left);
        flag++;
        if(flag==2*N)
            printf("%d",BT->Data);
        else
        printf("%d ",BT->Data);
        InorderTraversal(BT->Right);
        
    }
}
void PostorderTraversal( BiTree BT ){
    if(BT){
        PostorderTraversal(BT->Left);
        PostorderTraversal(BT->Right);
        flag++;
        if(flag==3*N)
        printf("%d",BT->Data);
        else
        printf("%d ",BT->Data);
    }
}
int main(){
    int i,a[10000][15],b[10000];
    scanf("%d",&N);
    for(i=1;i<=N;i++){
        scanf("%d%d%d",&b[i],&a[i][0],&a[i][1]);
    }
     BiTree BT; 
     BT=CreaTree(a,1);
     PreorderTraversal(BT);
     printf("\n");
     InorderTraversal(BT);
     printf("\n");
     PostorderTraversal(BT);
}
相关推荐
Dontla25 分钟前
Makefile介绍(Makefile教程)(C/C++编译构建、自动化构建工具)
c语言·c++·自动化
奶黄小甜包35 分钟前
C语言零基础第18讲:自定义类型—结构体
c语言·数据结构·笔记·学习
一支闲人1 小时前
C语言相关简单数据结构:双向链表
c语言·数据结构·链表·基础知识·适用于新手小白
John.Lewis2 小时前
数据结构初阶(19)外排序·文件归并排序的实现
c语言·数据结构·排序算法
John.Lewis2 小时前
数据结构初阶(16)排序算法——归并排序
c语言·数据结构·排序算法
wearegogog1232 小时前
C语言中的输入输出函数:构建程序交互的基石
c语言·开发语言·交互
艾莉丝努力练剑14 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
Cx330❀16 小时前
【数据结构初阶】--排序(五):计数排序,排序算法复杂度对比和稳定性分析
c语言·数据结构·经验分享·笔记·算法·排序算法
..过云雨17 小时前
01.【数据结构-C语言】数据结构概念&算法效率(时间复杂度和空间复杂度)
c语言·数据结构·笔记·学习
谱写秋天19 小时前
在STM32F103上进行FreeRTOS移植和配置(STM32CubeIDE)
c语言·stm32·单片机·freertos