二叉树2的算法

(以下代码非原创)
#include<assert.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct _treenode
{
int data;
struct _treenode *lchild;
struct _treenode *rchild;
}Tnode,Tree;
void binarytree_create(Tree **Root)
{
int a = 0;
printf("\r\n input jiedian number:");
scanf("%d",&a);
if (a==0)
{
*Root = NULL;
}
else
{
*Root = (Tnode *)malloc(sizeof(Tnode));
if (*Root == NULL)
{
return;
}
(*Root)->data = a;
printf("\r\n create %d de lchild:",a);
binarytree_create(&((*Root)->lchild));
printf("\r\n create %d de rchild:",a);
binarytree_create(&((*Root)->rchild));
}
return ;
}
void binarytree_destory(Tree *root)
{
if (root == NULL)
{
return;
}

binarytree_destory(root->lchild);
binarytree_destory(root->rchild);
free(root);

}
/先序遍历:根结点–》左子树—》右子树/
void binarytree_preorder(Tree *root)
{
if (root == NULL)
{
return;
}
printf(" %d “,root->data);
binarytree_preorder(root->lchild);
binarytree_preorder(root->rchild);
return;
}
/中序遍历:左子树–》跟节点—》右子树/
void binarytree_inorder(Tree *root)
{
if (root == NULL)
{
return;
}
binarytree_inorder(root->lchild);
printf(” %d “,root->data);
binarytree_inorder(root->rchild);
return;
}
/后序遍历:左子树—》右子树-》根节点/
void binarytree_postorder(Tree *root)
{
if (root == NULL)
{
return;
}
binarytree_postorder(root->lchild);
binarytree_postorder(root->rchild);
printf(” %d ",root->data);
return;
}
/打印叶子节点/
void binarytree_printfleaf(Tree *root)
{
if (root == NULL)
{
return;
}

if ((root->lchild == NULL) && (root->rchild == NULL))
{
	printf("%d ",root->data);
}
else
{
	binarytree_printfleaf(root->lchild);
	binarytree_printfleaf(root->rchild);
}

}
/打印叶子的个数/
int binarytree_getleafnum(Tree*root)
{
if (root == NULL)
{
return 0;
}
if ((root->lchild == NULL) && (root->rchild == NULL))
{
return 1;
}
return binarytree_getleafnum(root->lchild) + binarytree_getleafnum(root->rchild);
}
/打印数的高度/
int binarytree_gethigh(Tree *root)
{
int lhigh = 0;
int rhigh = 0;
if (root == NULL)
{
return 0;
}
lhigh = binarytree_gethigh(root->lchild);
rhigh = binarytree_gethigh(root->rchild);
return ((lhigh > rhigh)?(lhigh + 1):(rhigh + 1));
}
int main()
{
Tree *root = NULL;
printf("\r\n create Tree:");
binarytree_create(&root);
printf("\r\n preorder:");
binarytree_preorder(root);
printf("\r\n inorder:");
binarytree_inorder(root);
printf("\r\n postorder:");
binarytree_postorder(root);
printf("\r\n printfleaf:");
binarytree_printfleaf(root);
printf("\r\n getleafnum:%d",binarytree_getleafnum(root));
printf("\r\n tree height:%d",binarytree_gethigh(root));
binarytree_destory(root);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值