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

结果展示:

相关推荐
he___H4 小时前
数据结构-移位
数据结构
电子_咸鱼5 小时前
LeetCode——Hot 100【电话号码的字母组合】
数据结构·算法·leetcode·链表·职场和发展·贪心算法·深度优先
仰泳的熊猫5 小时前
LeetCode:785. 判断二分图
数据结构·c++·算法·leetcode
haoly19897 小时前
数据结构和算法篇-归并排序的两个视角-迭代和递归
数据结构·算法·归并排序
小梁努力敲代码7 小时前
java数据结构--List的介绍
java·开发语言·数据结构
Code小翊10 小时前
归并排序基础理解
数据结构·算法·排序算法
.小小陈.10 小时前
数据结构2:单链表
c语言·开发语言·数据结构·笔记·学习方法
草莓工作室10 小时前
数据结构4:线性表3-链式存储的线性表
数据结构
雾时之林10 小时前
数据结构--单链表
数据结构
Camel卡蒙10 小时前
数据结构——二叉搜索树Binary Search Tree(介绍、Java实现增删查改、中序遍历等)
java·开发语言·数据结构