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

结果展示:

相关推荐
月盈缺3 小时前
学习嵌入式的第二十二天——数据结构——双向链表
数据结构·学习·链表
科大饭桶4 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
躲在云朵里`5 小时前
深入理解数据结构:从数组、链表到B树家族
数据结构·b树
1白天的黑夜18 小时前
链表-24.两两交换链表中的结点-力扣(LeetCode)
数据结构·leetcode·链表
养成系小王14 小时前
四大常用排序算法
数据结构·算法·排序算法
闪电麦坤9516 小时前
数据结构:从前序遍历序列重建一棵二叉搜索树 (Generating from Preorder)
数据结构··二叉搜索树
闪电麦坤9516 小时前
数据结构:二叉树的遍历 (Binary Tree Traversals)
数据结构·二叉树·
球king16 小时前
数据结构中邻接矩阵中的无向图和有向图
数据结构
野渡拾光18 小时前
【考研408数据结构-05】 串与KMP算法:模式匹配的艺术
数据结构·考研·算法
pusue_the_sun1 天前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树