数据结构-day7

二叉树创建、遍历、计算结点、计算深度

head.h

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

typedef char datatype;
typedef struct Btree{
	datatype data;
	struct Btree *lchild;
	struct Btree *rchild;
}*btree;

btree create();
void insert_child(datatype e,btree tree);
void first(btree tree);
void mid(btree tree);
void last(btree tree);
void count(btree tree,int *n0,int *n1,int *n2);
int high(btree tree);

main.c

cpp 复制代码
#include "head.h"
int main(int argc, const char *argv[]){
        btree tr=create();
        first(tr);
        puts("");
        mid(tr);
        puts("");
        last(tr);
        puts("");
        int *n0,*n1,*n2,N0,N1,N2;
        n0=&N0,n1=&N1,n2=&N2;
        *n0=0,*n1=0,*n2=0;
        count(tr,n0,n1,n2);
        printf("%d %d %d\n",*n0,*n1,*n2);
        printf("深度为%d\n",high(tr));
        return 0;
}

test.c

cpp 复制代码
#include "head.h"

btree create_node(){
	btree p=(btree)malloc(sizeof(struct Btree));
	p->data=0;
	p->lchild=NULL;
	p->rchild=NULL;
}
btree create(){
	datatype e;
	printf("please input e:");
	scanf("%c",&e);
	getchar();
	if(e=='#')
		return NULL;
	btree tr=create_node();
	tr->data=e;
	puts("创建左孩子");
	tr->lchild=create();
	puts("创建右孩子");
	tr->rchild=create();
	return tr;
}
void first(btree tree){
	if(!tree)
		return;
	printf("%c ",tree->data);
	first(tree->lchild);
	first(tree->rchild);
}
void mid(btree tree){
        if(!tree)
                return;
        mid(tree->lchild);
	printf("%c ",tree->data);
        mid(tree->rchild);
}
void last(btree tree){
        if(!tree)
                return;
        last(tree->lchild);
	last(tree->rchild);
	printf("%c ",tree->data);
}

void count(btree tree,int *n0,int *n1,int *n2){
	if(!tree)
		return;
	if(!tree->lchild&&!tree->rchild)
		++*n0;
	else if(tree->lchild&&tree->rchild)
		++*n2;
	else
		++*n1;
	count(tree->lchild,n0,n1,n2);
	count(tree->rchild,n0,n1,n2);
}

int high(btree tree){
	if(!tree)
		return 0;
	int left=1+high(tree->lchild);
	int right=1+high(tree->rchild);
	return left>right?left:right;
}

结果展示:

相关推荐
苏小瀚1 天前
[数据结构] 排序
数据结构
睡不醒的kun1 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌1 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long1 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn1 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap
我星期八休息1 天前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list
和编程干到底1 天前
数据结构 栈和队列、树
数据结构·算法
爱编程的化学家1 天前
代码随想录算法训练营第十一天--二叉树2 || 226.翻转二叉树 / 101.对称二叉树 / 104.二叉树的最大深度 / 111.二叉树的最小深度
数据结构·c++·算法·leetcode·二叉树·代码随想录
shan&cen1 天前
Day04 前缀和&差分 1109. 航班预订统计 、304. 二维区域和检索 - 矩阵不可变
java·数据结构·算法
屁股割了还要学1 天前
【数据结构入门】排序算法(4)归并排序
c语言·数据结构·学习·算法·排序算法