数据结构-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;
}

结果展示:

相关推荐
爱读书的小胖13 分钟前
LeetCode 27. 移除元素(C)解题分析
数据结构·算法
爱读书的小胖36 分钟前
Codewars: A Brave New Wordle(C)解题分析
c语言·数据结构·算法
Escalating_xu37 分钟前
【数据结构】顺序表的应用:动态通讯录项目与双指针经典算法
c语言·数据结构·算法
从小白到软工2 小时前
C语言(中)预告
c语言·数据结构·经验分享·ai编程
垆边人似月.2 小时前
华为题:任务调度
数据结构·c++·算法
Logic1012 小时前
C语言/数据结构字符串题解:解压缩“字符+次数“格式——多位数字处理与字符串还原
c语言·数据结构·字符串·模拟·时间复杂度·空间复杂度·算法题
信奥卷王2 小时前
[GESP202506 六级] 最大因数(含视频)
数据结构·算法
局部有解2 小时前
Leetcode - 42 接雨水(一维)
数据结构·c++·算法·leetcode
专注API从业者3 小时前
告别手工盯盘:用 Open‑Claw 搭建电商商品自动化监控与数据分析实战
运维·数据结构·数据挖掘·数据分析·自动化
Logic1013 小时前
C语言/数据结构位运算题解:异或XOR找出糖葫芦派对中的“独一无二山楂果数量“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质