#include <stdio.h>
#include <stdlib.h>
typedef struct BiTNode {
int data;
struct BiTNode* lChild;
struct BiTNode* rChild;
} BiTNode, *BiTTree;
// 创建二叉排序树
void CreateBiTTree(BiTTree* b, int data) {
if (*b == NULL) {
*b = (BiTNode*)malloc(sizeof(BiTNode));
(*b)->data = data;
(*b)->lChild = NULL;
(*b)->rChild = NULL;
} else {
if (data < (*b)->data) {
CreateBiTTree(&((*b)->lChild), data);
} else {
CreateBiTTree(&((*b)->rChild), data);
}
}
}
// 查找节点
BiTNode* FindNode(BiTNode* b, int x) {
BiTNode* p;
if (b == NULL) {
return NULL;
} else if (b->data == x) {
return b;
} else {
p = FindNode(b->lChild, x);
if (p != NULL) {
return p;
} else {
return FindNode(b->rChild, x);
}
}
}
// 删除二叉树
void DestroyBiTTree(BiTNode* b) {
if (b != NULL) {
DestroyBiTTree(b->lChild);
DestroyBiTTree(b->rChild);
free(b);
}
}
// 输出树高的算法
int BiTNodeDepth(BiTNode* b) {
int lChildDep, rChildDep;
if (b == NULL) {
return 0;
} else {
lChildDep = BiTNodeDepth(b->lChild);
rChildDep = BiTNodeDepth(b->rChild);
return (lChildDep > rChildDep) ? (lChildDep + 1) : (rChildDep + 1);
}
}
// 统计二叉树的结点数目
int CountNode(BiTNode* b) {
if (b == NULL) {
return 0;
} else {
return CountNode(b->lChild) + CountNode(b->rChild) + 1;
}
}
int main() {
BiTNode* root = NULL;
// 创建二叉排序树
int data[] = {8, 3, 10, 1, 6, 14, 4, 7, 13};
int n = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < n; i++) {
CreateBiTTree(&root, data[i]);
}
// 测试查找节点
int x = 6;
BiTNode* node = FindNode(root, x);
if (node != NULL) {
printf("Node with data %d found in the tree.\n", x);
} else {
printf("Node with data %d not found in the tree.\n", x);
}
// 测试输出树高
int depth = BiTNodeDepth(root);
printf("Tree depth: %d\n", depth);
// 测试统计结点数目
int nodeCount = CountNode(root);
printf("Total nodes in the tree: %d\n", nodeCount);
// 销毁二叉树
DestroyBiTTree(root);
root = NULL;
return 0;
}
// 8
// / \
// 3 10
// / \ \
// 1 6 14
// / \ /
// 4 7 13
二叉树的基本操作
最新推荐文章于 2024-05-21 23:16:53 发布