(以输入字符为例)
通过中序、后序建树
struct tree *creat(char *a, char *b, int n) // 通过中序、后序建树
{
if(n <= 0) return NULL;
struct tree *root;
root = (struct tree *)malloc(sizeof (struct tree));
root->data = b[n - 1];
int i;
for(i = 0; i < n; i++)
{
if(a[i] == b[n - 1]) break;
}
root->l = creat(a, b, i);
root->r = creat(a + i + 1, b + i, n - i - 1);
return root;
};
通过前(先)序、中序建树
struct tree *creat(char a[], char b[], int n) // 通过前(先)序、中序建树
{
if(n <= 0) return NULL;
struct tree *root;
root = (struct tree *)malloc(sizeof(struct tree));
root->data = a[0];
int i;
for(i = 0; i < n; i++)
{
if(b[i] == a[0]) break;
}
root->l = creat(a + 1, b, i);
root->r = creat(a + i + 1, b + i + 1, n - i - 1);
return root;
};
先序给定空结点建树
struct tree *creat(char *a) // 先序给定空结点建树
{
struct tree *root;
if(a[++i] == ',') root = NULL; // 定义全局变量i,在main函数中赋值为-1
else
{
root = (struct tree *)malloc(sizeof(struct tree));
root->data = a[i]; // 注意这里不需要再++
root->l = creat(a);
root->r = creat(a);
}
return root;
};
层序输出
void at_out(struct tree *root) // 层序输出
{
if(root == NULL) return;
int t = 0, i = 0;
struct tree *s[100], *q; //指针类型数组
s[0] = root;
while(t <= i)
{
q = s[t++];
printf("%c", q->data);
if(q->l != NULL)
{
s[++i] = q->l;
}
if(q->r != NULL)
{
s[++i] = q->r;
}
}
}
// 前(先)序输出:根左右
void pre_out(struct tree *root)
{
if(root)
{
printf("%c", root->data);
pre_out(root->l);
pre_out(root->r);
}
}
// 中序输出:左根右
void mid_out(struct tree *root)
{
if(root)
{
pre_out(root->l);
printf("%c", root->data);
pre_out(root->r);
}
}
// 后序输出:左右根
void aft_out(struct tree *root)
{
if(root)
{
pre_out(root->l);
pre_out(root->r);
printf("%c", root->data);
}
}
求最大深度,求高度
int depth(struct tree *root) // 求最大深度,求高度
{
int ld, rd;
if(!root) return 0;
else
{
ld = depth(root->l);
rd = depth(root->r);
return ld > rd ? ld + 1 : rd + 1;
}
}
查找叶子结点(统计个数)
void leaf(struct tree *root) // 查找叶子结点(统计个数)
{
if(root)
{
leaf(root->l);
leaf(root->r);
if(!root->l && !root->r)
{
leaf_num++;
}
}
}