#include <stdio.h>
#include <malloc.h>
#define NULL 0
typedef struct tree
{
int data;
struct tree *left, *right;
}ElemBT;
void create_btree(ElemBT *root, int list[], int n) /*n表示list数组中元素的个数*/
{
int i;
ElemBT *current, *parent, *p;
for(i = 1; i < n; i++)
{
p = (ElemBT *)malloc(sizeof(ElemBT));
p->left = p->right = NULL;
p->data = list[i];
current = root;
while(current != NULL)
{
parent = current;
if(current->data > p->data)
current = current->left;
else
current = current->right;
}
if(parent->data > p->data)
parent->left = p;
else
parent->right = p;
}
}
void pre_order(ElemBT *root) /*前序遍历*/
{
if(root) /*root != NULL*/
{
printf("%4d", root->data); /*根结点打印*/
pre_order(root->left); /*左子树遍历*/
pre_order(root->right); /*右子树遍历*/
}
else
{
return;
}
}
void in_order(ElemBT *root) /*中序遍历*/
{
if(root) /*root != NULL*/
{
in_order(root->left); /*左子树遍历*/
printf("%4d", root->data); /*根结点打印*/
in_order(root->right); /*右子树遍历*/
}
else
{
return;
}
}
void post_order(ElemBT *root) /*后序遍历*/
{
if(root) /*root != NULL*/
{
post_order(root->left); /*左子树遍历*/
post_order(root->right); /*右子树遍历*/
printf("%4d", root->data); /*根结点打印*/
}
else
{
return;
}
}
int node_count(ElemBT *root) /*二叉树结点个数统计*/
{
int cnt = 0;
if(root)
{
cnt += node_count(root->left);
cnt += node_count(root->right);
cnt ++; /*根节点*/
}
return cnt;
}
/*
int node_count(ElemBT *root) //结点个数统计
{
if(root == NULL)
return 0;
else
return (node_count(root->right)+node_count(root->left)+1);
}
*/
int btree_depth(ElemBT *root) /*二叉树的深度*/
{
int d1 = 0, d2 = 0;
if(root == NULL)
return 0;
else
{
d1 = btree_depth(root->left);
d2 = btree_depth(root->right);
return (d1>d2 ? d1+1 : d2+1);
}
}
int leaf_count(ElemBT *root) /*统计叶子结点个数*/
{
if(!root)
return 0;
if(!root->left && !root->right)
return 1;
else
return (leaf_count(root->left)+leaf_count(root->right));
}
int main()
{
int list[7] = {30, 18, 16, 25, 34, 7, 31};
ElemBT *root;
root = (ElemBT *)malloc(sizeof(ElemBT));
root->data = list[0];
root->left = root->right = NULL;
create_btree(root, list, 7);
printf("pre_order:\n");
pre_order(root);
printf("\n");
printf("in_order:\n");
in_order(root);
printf("\n");
printf("post_order:\n");
post_order(root);
printf("\n");
printf("Node number is: %d\n", node_count(root));
printf("Btree depth is: %d\n", btree_depth(root));
printf("Leaf node number is: %d\n", leaf_count(root));
return 0;
}
程序运行截图:
二叉树(二)——遍历、深度统计、叶子结点统计、结点统计,布布扣,bubuko.com
原文地址:http://blog.csdn.net/laoniu_c/article/details/38397437