-------------------------
写了个比较简单的,包括建立二叉树,还有你需要的递归函数,不懂可追问
#include <stdio.h>
#include <malloc.h>
#define CURRENT 0
#define LEFT 1
#define RIGHT 2
typedef struct BiTree
{
char data; //数据
BiTree* lchild; //左孩子节点
BiTree* rchild; //右孩子节点
BiTree* parent; //父节点
}BiTree;
void InitBiTree(BiTree* tree) //构造空二叉树
{
tree = NULL;
}
void CreateTree(BiTree* tree, char data) //给二叉树赋值
{
tree->data = data;
tree->parent = NULL;
tree->lchild = NULL;
tree->rchild = NULL;
}
int InsertChild(BiTree* tree, int pos, char data) //给孩子节点赋值
{
if (pos == LEFT)
{
if (tree->lchild != NULL)
{
printf("insert left child error!\n");
return false;
}
BiTree* t = (BiTree*)malloc(sizeof(BiTree));
tree->lchild = t;
t->data = data;
t->lchild = NULL;
t->rchild = NULL;
t->parent = tree;
return 1;
}
else if (pos == RIGHT)
{
if (tree->rchild != NULL)
{
printf("insert right child error!\n");
return 0;
}
BiTree* t = (BiTree*)malloc(sizeof(BiTree));
tree->rchild = t;
t->data = data;
t->lchild = NULL;
t->rchild = NULL;
t->parent = tree;
return 1;
}
return 0;
}
int PreOrderTraverse(BiTree* tree, int* countchildren, int* countleaves) // 递归函数
{
BiTree* p = tree;
if (p)
{
(*countchildren)++; // 如果那个节点有数据,就增加子节点数
int lnull, runll;
if (lnull = PreOrderTraverse(p->lchild, countchildren, countleaves))
{
if (runll = PreOrderTraverse(p->rchild, countchildren, countleaves))
{
if (lnull == -1 && runll == -1) // 如果左右节点都为空,则增加叶子节点数
{
(*countleaves)++;
}
return 1;
}
}
return 0;
}
else
{
return -1;
}
}
int main()
{
BiTree bt;
int countchildren = 0;
int countleaves = 0;
InitBiTree(&bt);
CreateTree(&bt, 's');
InsertChild(&bt, LEFT, 'i');
InsertChild(bt.lchild, LEFT, 'A');
InsertChild(bt.lchild->lchild, LEFT, 'x');
InsertChild(bt.lchild, RIGHT, 'B');
InsertChild(bt.lchild->rchild, RIGHT, 'y');
InsertChild(&bt, RIGHT, 'o');
PreOrderTraverse(&bt, &countchildren, &countleaves);
printf("countchildren : %d\n", countchildren);
printf("countleaves : %d\n", countleaves);
return 0;
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。