二叉树(纯代码)

tree.h

#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>

typedef int BTDatatype;
typedef struct BinaryTreeNode
{
	BTDatatype data;
	struct BinaryTreeNode* left;
	struct BinaryTreeNode* right;
}BTNode;

//申请节点
BTNode* BuyNode(BTDatatype x);
//前序遍历打印
void PreOrder(BTNode* root);
//创造二叉树
BTNode* CreatTree();
//二叉树元素个数
int TreeSize(BTNode* root);
//二叉树的深度
int TreeHeight(BTNode*);
//求第k层节点个数
int TreeLevel(BTNode* root, int k);
//查找元素
BTNode* BinaryTreeFind(BTNode* root, BTDatatype x);

tree.c

#include "tree.h"
//前序打印
void PreOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	printf("%d ", root->data);
	PreOrder(root->left);
	PreOrder(root->right);
}
//申请节点
BTNode* BuyNode(BTDatatype x)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	if (node == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	node->data = x;
	node->left = NULL;
	node->right = NULL;
	return node;
}

BTNode* CreatTree()
{
	BTNode* nodel1 = BuyNode(1);
	BTNode* nodel2 = BuyNode(3);
	BTNode* nodel3 = BuyNode(9);
	BTNode* nodel4 = BuyNode(10);
	BTNode* nodel5 = BuyNode(2);
	BTNode* nodel6 = BuyNode(12);
	BTNode* nodel7 = BuyNode(16);
	BTNode* nodel8 = BuyNode(17);
	nodel1->left = nodel2;
	nodel1->right = nodel6;
	nodel2->left = nodel3;
	nodel2->right = nodel4;
	nodel4->left = nodel5;
	nodel6->right = nodel7;
	nodel7->right = nodel8;
	return nodel1;
}


//二叉树元素个数
int TreeSize(BTNode* root)
{
	return root == NULL ? 0 :
		TreeSize(root->left)
		+ TreeSize(root->right)
		+1;
}

//二叉树的深度
int TreeHeight(BTNode*root)
{
	if (root == NULL)
		return 0;
	int LeftHeight = TreeHeight(root->left);
	int RightHeight = TreeHeight(root->right);
	return LeftHeight > RightHeight
		? LeftHeight+1 : RightHeight+1;
}

//求第k层节点个数
int TreeLevel(BTNode* root, int k)
{
	assert(k > 0);
	if (root == NULL)
		return 0;
	if (k == 1)
		return 1;
	return TreeLevel(root->left, k - 1) 
		+ TreeLevel(root->right, k - 1);
}
//查找元素
BTNode* BinaryTreeFind(BTNode* root, BTDatatype x)
{
	if (root == NULL)
		return NULL;
	if (root->data == x)
		return root;
	BTNode* reft = BinaryTreeFind(root->left, x);
	if (reft)
	{
		return reft;
	}
	BTNode* rreft = BinaryTreeFind(root->right, x);
	if (rreft)
	{
		return rreft;
	}
	return NULL;
}

test.c

#include"tree.h"
void BTNodeTest()
{
	BTNode* ret=CreatTree();
	PreOrder(ret);
	printf("\n%d\n", TreeSize(ret));
	printf("%p\n",BinaryTreeFind(ret, 9));
	printf("%d\n", TreeHeight(ret));
	printf("%d\n", TreeLevel(ret,4));
}

int main(void)
{
	BTNodeTest();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值