方法一:
//用先序,中序,后序的方法遞歸遍歷二叉樹
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node *lchild,*rchild;
}BiNode,*Bitree;
//創建一個二叉樹
void Inittree(Bitree e)
{
char x;
scanf("%d",&x);
if(x==0) e=NULL;
else
{
e=(BiNode *)malloc(sizeof(BiNode));
e->data=x;
Inittree(e->lchild);
Inittree(e->rchild);
}
}
//用先序遍歷二叉樹
void preorder(Bitree t)
{
if(t==NULL)
return ;
printf("%d\n",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
//中序遍歷二叉樹
void Inorder(Bitree t)
{
if(t==NULL)
return ;
Inorder(t->lchild);
printf("%d\n",t->data);
Inorder(t->rchild);
}
//后序遍歷二叉樹
void posorder(Bitree t)
{
if(t==NULL)
return ;
posorder(t->lchild);
posorder(t->rchild);
printf("%d\n",t->data);
}
//用遞歸的方法計算二叉樹的結點的個數
int countnode(Bitree t)
{
if(t==NULL)
return 0;
else
{
return countnode(t->lchild)+countnode(t->rchild)+1;
}
}
int main()
{
Bitree t;
int change=-1;
int num;
Inittree(t);
printf("1:先序遍歷\n");
printf("2:中序遍歷\n");
printf("3:后序遍歷\n");
printf("4:計算樹的結點個數\n");
printf("請輸出選擇:\n");
scanf("%d",&change);
switch(change)
{
case 1:
preorder(t);
printf("\n\n");
break;
case 2:
Inorder(t);
printf("\n\n");
break;
case 3:
posorder(t);
printf("\n\n");
break;
case 4:
countnode(t);
num=countnode(t);
printf("%d\n\n",num);
break;
default :
printf("ERROR!\n");
}
return 0;
}
方法二:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
//定義二叉樹
typedef struct node{
int data;//數據元素
struct node *left;//指向左子樹
struct node *right;//指向右子樹
}BTree;
//構造二叉樹:遞歸方式
int BTreeCreate(BTree **tp)
{
//構造方法,或者說構造順序:從左子樹開始構造
int x;
scanf("%d",&x);
if(x<=0)
{
*tp=NULL;//指針為空,樹節點中的某個指針為空
return 0;
}
*tp=(BTree*)malloc(sizeof(BTree));//將樹節點中指針指向該地址空間
if(tp==NULL)
return 0;
(*tp)->data=x;
BTreeCreate(&((*tp)->left));
BTreeCreate(&((*tp)->right));
return 1;
}
//遍歷:前序遍歷,遞歸的方式,先根節點,再左子樹后右子樹
void PreOrder(BTree *tree)
{
if(tree==NULL)
{
return;
}
printf("%d ",tree->data);
PreOrder(tree->left);
PreOrder(tree->right);
}
//遍歷:中序遍歷,遞歸方式,先左子樹再根節點最后右子樹
void MidOrder(BTree *tree)
{
if(tree==NULL)
{
return;
}
MidOrder(tree->left);
printf("%d ",tree->data);
MidOrder(tree->right);
}
//遍歷:后序遍歷,遞歸方式,先左子樹再右子樹最后根節點
void PostOrder(BTree *tree)
{
if(tree==NULL)
{
return;
}
PostOrder(tree->left);
PostOrder(tree->right);
printf("%d ",tree->data);
}
int countnode(BTree *tree)
{
if(tree==NULL)
return 0;
else
return countnode(tree->left)+countnode(tree->right)+1;
}
int main()
{
//二叉樹構建
BTree *tree;
printf("Create binary tree:\n");
BTreeCreate(&tree);
//前序遍歷
printf("Pre order:\n");
PreOrder(tree);
printf("\n");
//中序遍歷
printf("Mid order:\n");
MidOrder(tree);
printf("\n");
//后序遍歷
printf("Post order:\n");
PostOrder(tree);
printf("\n");
//計算二叉樹節點數目
printf("輸出點的數目:\n");
int num=countnode(tree);
printf("%d\n",num);
return 0;
}
