数据结构:二叉树基本操作
创建 复制 求树深度 求叶子节点个数
本贴借鉴原文章链接 预查看点击此处
× 代表该结点不存在
#include<stdio.h>
#include<stdlib.h>
struct tree{
int date;
struct tree* left;
struct tree* right;
};//结点结构
typedef tree node;
typedef node* ptree;
ptree creatree(int* date,int num) {
ptree tempT;//临时根节点
if (date[num] == 0 || num > 15) {
return NULL;
}//数据为空或建树完成
else {
tempT = (ptree)malloc(sizeof(node));//为新节点申请内存
tempT->date = date[num];//存储数据
tempT->left = creatree(date, 2 * num);//递归建左子树
tempT->right = creatree(date, 2 * num + 1);//递归建右子树
return tempT;
}
}
ptree copytree(ptree T) {
ptree tempT;
if (T != NULL) {
tempT = (ptree)malloc(sizeof(node));
tempT->date = T->date;//根节点复制
tempT->left = copytree(T->left);//递归复制左子树
tempT->right = copytree(T->right);//递归复制右子树
return tempT;
}
else
return NULL;
}
void pribtio(ptree T) {
//中序遍历二叉树
if (T != NULL)
{
//遍历左子树
pribtio(T->left);
//遍历根节点
printf("%2d", T->date);
//遍历右子树
pribtio(T->right);
}
}
int depth(ptree T) {//求树的深度 即左右子树深度较大者加一
static int m=0,n=0;
if (T != NULL) {
m = depth(T->left);
n = depth(T->right);
if (m > n)
return m + 1;
else
return n + 1;
}
else
return 0;
}
int countnode(ptree T,int & node) {
if (T == NULL)
return node;
else {
if (T->left == NULL && T->right == NULL)
node++;
countnode(T->left, node);
countnode(T->right, node);
return node;
}
}
int main(void){
ptree T = NULL;
ptree newT = NULL;
int deep;
int nodedate[16] = { 0,5,4,6,2,0,0,8,1,3,0,0,0,0,7,9 };
T = creatree(nodedate,1);//建树
printf("中序遍历结果:\n");
pribtio(T);//中序遍历二叉树
printf("\n");
deep=depth(T);
printf("此二叉树的高度是%d\n",deep);
codenum = countnode(T, codenum);
printf("叶子结点的个数为%d\n", codenum);
newT = copytree(T);
printf("中序遍历复制的二叉树结果:\n");
pribtio(newT);//中序遍历复制二叉树
return 0;
}
运行结果如下