#include<stdio.h>
#include<stdlib.h>
//#include<string.h>
typedef struct SNode
{
char x;
SNode *Lchild;
SNode *Rchild;
}BiTNode,* BiTree;
BiTree creatBiTree() //有返回值的创建树 调用一级指针
{
BiTree root;
char ch;
ch=getchar();
if(ch=='#')
root=NULL;
else
{
root=(BiTree)malloc(sizeof(BiTNode));
root->x=ch;
root->Lchild=creatBiTree();
root->Rchild=creatBiTree();
}
return root;
}
void creatBiTree(BiTree *root) //(引用二级指针 无返回值 传递的为*root的地址 相当于在这个函数中root存的
{ //是传来root的地址 而*root则为传来的root)
char ch;
ch=getchar();
if(ch=='#')
(*root)=NULL;
else
{
*root=(BiTree)malloc(sizeof(BiTNode));
(*root)->x=ch;
creatBiTree(&((*root)->Lchild));
creatBiTree(&((*root)->Rchild));
}
}
void PreOrder(BiTree root) //先序遍历
{
if(root)
{
printf("%5c",root->x);
PreOrder(root->Lchild);
PreOrder(root->Rchild);
}
}
void Inorder(BiTree root) //中序遍历
{
if(root)
{
Inorder(root->Lchild);
printf("%5c",root->x);
Inorder(root->Rchild);
}
}
void PostOrder(BiTree root) //后续遍历
{
if(root)
{
PostOrder(root->Lchild);
PostOrder(root->Rchild);
printf("%4c",root->x);
}
}
int count=0; //先序遍历统计二叉树中的节点数
void Orderjiedian(BiTree root)
{
if(root)
{
count++;
Orderjiedian(root->Lchild);
Orderjiedian(root->Rchild);
}
}
void printyezi(BiTree root) //遍历输出二叉树叶子节点(相比遍历只多了个判断没有左右节点时输出)
{
if(root)
{
printyezi(root->Lchild);
if(root->Lchild==NULL&&root->Rchild==NULL)
printf("%4c",root->x);
printyezi(root->Rchild);
}
}
int leaf(BiTree root) //后序遍历统计叶子节点数目(必须为后续)
{
int nl,nr;
if(root==NULL)
return 0;
if((root->Lchild==NULL)&&(root->Rchild==NULL))
return 1;
nl=leaf(root->Lchild);
nr=leaf(root->Rchild);
return (nl+nr);
}
int PostTreeDepth(BiTree root) //求二叉树的高度 递归有返回值调用
{
int hl,hr,h;
if(root==NULL)
return 0;
else
{
hl=PostTreeDepth(root->Lchild);
hr=PostTreeDepth(root->Rchild);
h=(hl>hr? hl:hr)+1;
return h;
}
}
int main(void)
{
BiTree root;
// creatBiTree(&root);
root=creatBiTree();
printf("\n");
printf("%d",PostTreeDepth( root));
// printf("%d",count);
printf("\n");
return 0;
}
总结:
树中递归无返回值 其实就相当于先把函数中的左或者右先遍历完 找到最后一层 从最后一层开始 逐个往上走 直到这个节点的左右叶子遍历完
再进入它的上一个节点 只有当一个节点他的子叶遍历完 才会进入它上一个节点
树中递归有返回值 其实也就相当于从最后一个节点开始逐一返回 叶子节点的左右孩子相加作为上一个双亲节点的子叶
创建树时不能用一级指针的传递 因为开辟空间是在调用函数中的 在函数结束时释放开辟的空间 所以等于无操作