#include "stdio.h"
#include "malloc.h"
typedef struct tree_node
{
int date;
struct tree_node *L_child;
struct tree_node *R_child;
}node;
void create_tree(node * &tree)
{
int ch;
scanf("%d", &ch);
if(ch!=0)
{
tree=(node *)malloc(sizeof(node));
tree->date=ch;
create_tree(tree->L_child);
create_tree(tree->R_child);
}
else //这一句必须有 ,不然后期遍历树时,则无法判断子树是否为空(null)
tree=NULL;
}
void qianxu_view(node *tree)
{
if(tree)
{
printf("%d",tree->date );
qianxu_view(tree->L_child);
qianxu_view(tree->R_child);
}
}
void zhongxu_view(node *tree)
{
if(tree)
{
zhongxu_view(tree->L_child);
printf("%d",tree->date);
zhongxu_view(tree->R_child);
}
}
int max(int a ,int b)
{
if(a>b)
return a;
else
return b;
}
int tree_dep(node *tree )//二叉树的深度
{
if(tree->L_child==NULL && tree->R_child==NULL)
return 1;
else if(tree->L_child==NULL && tree->R_child!=NULL)
return tree_dep(tree->R_child)+1;
else if(tree->L_child!=NULL && tree->R_child==NULL)
return tree_dep(tree->L_child)+1;
else if(tree->L_child!=NULL && tree->R_child!=NULL)
return max(tree_dep(tree->L_child),tree_dep(tree->R_child))+1;
}
int main()
{
node *tree;
//这为什么事 node*,而不是node,因为程序后面要的调用malloc来开辟空间
//malloc原型是 extern void *malloc(unsigned int num_bytes);
//可以看到malloc函数返回的是(void *)类型,是一个指针类型,所以要用 node*;
create_tree(tree);
if(tree!=NULL)
{
printf("先序%d:");
qianxu_view(tree);
printf("中序%d:");
zhongxu_view(tree);
printf("\n\n深度--%d\n",tree_dep(tree));
}
}
求深度的时候用到动态规划:
递归方程:dep(tree))= max { dep(tree->L) , dep(tree->R)} + 1;
边界条件:当 tree->L && tree ->L 都为NULL时,dep(tree)为1;
树的结构为:
树的输入结构: