#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;
}
總結:
樹中遞歸無返回值 其實就相當於先把函數中的左或者右先遍歷完 找到最後一層 從最後一層開始 逐個往上走 直到這個節點的左右葉子遍歷完
再進入它的上一個節點 只有當一個節點他的子葉遍歷完 纔會進入它上一個節點
樹中遞歸有返回值 其實也就相當於從最後一個節點開始逐一返回 葉子節點的左右孩子相加作爲上一個雙親節點的子葉
創建樹時不能用一級指針的傳遞 因爲開闢空間是在調用函數中的 在函數結束時釋放開闢的空間 所以等於無操作