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

结果展示:

相关推荐
罗湖老棍子2 小时前
强迫症冒险家的任务清单:字典序最小拓扑排序
数据结构·算法·图论·拓扑排序
数智工坊3 小时前
【操作系统-文件管理】
数据结构·数据库
芒克芒克4 小时前
数组去重进阶:一次遍历实现最多保留指定个数重复元素(O(n)时间+O(1)空间)
数据结构·算法
Fcy6484 小时前
⽤哈希表封装unordered_map和unordered_set(C++模拟实现)
数据结构·c++·散列表
一分之二~5 小时前
二叉树--层序遍历(迭代和递归)
数据结构·c++·算法·leetcode
散峰而望7 小时前
【基础算法】高精度运算深度解析与优化
数据结构·c++·算法·链表·贪心算法·推荐算法
C雨后彩虹7 小时前
中文分词模拟器
java·数据结构·算法·华为·面试
Remember_9937 小时前
【LeetCode精选算法】二分查找专题二
java·数据结构·算法·leetcode·哈希算法
学嵌入式的小杨同学8 小时前
【嵌入式 C 语言实战】栈、队列、二叉树核心解析:存储原理 + 应用场景 + 实现思路
linux·c语言·网络·数据结构·数据库·后端·spring
2401_841495648 小时前
【LeetCode刷题】删除链表的倒数第N个结点
数据结构·python·算法·leetcode·链表·遍历·双指针