构造一棵二叉树,并分别输出其先序遍历、中序遍历和后序遍历的结果

问题分析:二叉树先序遍历可利用非递归算法实现,首先使用一个栈stack,将根结点入栈,开始循环:从栈中退出当前结点p;先访问它,然后将其它右结点入栈,再将其左结点入栈,如此直到栈空为止。后序遍历也可使用非递归算法,根据后序遍历的二叉树的递归定义,转换成非递归函数时采用一个栈保存返回的结点,先遍历根结点的所有左结点并入栈,出栈一个结点,然后遍历该结点的右结点并入栈,再遍历该右结点的所有左结点并入栈,当一个结点的左右子树均访问后再访问该结点,如此,直到栈空。二叉树的中序遍历在此是用递归算法实现的(以达到递归和非递归算法都能运用的目的),先遍历左子树,然后访问根结点,最后遍历右子树,如此循环,直至访问完所有的结点。

实验步骤与源程序:
1.二叉树的遍历步骤:
1).定义二叉树的类型;
2) .构造头节点、左孩子、右孩子;
3).中序遍历;
4).先序遍历;
5).后序遍历
请各位高手帮哈忙,谢谢~~~~~~~~~

第1个回答  2010-12-05
#include<iostream>
using namespace std;

typedef struct BinaryTree
{
char data;
struct BinaryTree *lchild,*rchild;
}BinaryTree,*BiTree;

void CreateBiTree(BiTree &T)
{
char z;
if((z=getchar())==' ')
T=NULL;
else
{
T=(BinaryTree*)malloc(sizeof(BinaryTree));
T->data=z;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
//先序遍历
void preBiTree(BiTree T)
{
if(T!=NULL)
{
cout<<T->data;
preBiTree(T->lchild);
preBiTree(T->rchild);
}
}
//中序遍历
void InBiTree(BiTree T)
{
if(T!=NULL)
{
InBiTree(T->lchild);
cout<<T->data;
InBiTree(T->rchild);
}
}
//后序遍历
void PostBiTree(BiTree T)
{
if(T!=NULL)
{
PostBiTree(T->lchild);
PostBiTree(T->rchild);
cout<<T->data;
}
}
int Depth(BiTree T)
{
if(T==NULL)
{
return 0;
}
else
return 1+(Depth(T->lchild)>Depth(T->rchild)? Depth(T->lchild):Depth(T->rchild));
}

void main()
{
BiTree T;
cout<<"请输入相应二叉树:"<<endl;
CreateBiTree(T);
cout<<"二叉树的先序遍历为:"<<endl;
preBiTree(T);
cout<<endl;
cout<<"二叉树的中序遍历为:"<<endl;
InBiTree(T);
cout<<endl;
cout<<"二叉树的后序遍历为:"<<endl;
PostBiTree(T);
cout<<endl;
cout<<"二叉树的深度为:"<<endl;
cout<<Depth(T)<<endl;
}本回答被网友采纳
第2个回答  2010-12-01
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
int count=0;
typedef struct BiTNode {
int data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;

void CreateBiTree(BiTree &T){
int ch;
scanf("%d",&ch);
if(ch==0)T=NULL;
else{
if(!(T=(BiTNode * )malloc(sizeof(BiTNode)))) exit(-1);
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
int PreOrder(BiTree T)
{
if (!T) return 0;
printf("%d ",T->data);
PreOrder(T->lchild);
PreOrder(T->rchild);
return 1;
}
int InOrder(BiTree T)
{
if (!T) return 0;

InOrder(T->lchild);
printf("%d ",T->data);
InOrder(T->rchild);
return 1;
}
int PostOrder(BiTree T)
{
if (!T) return 0;

PostOrder(T->lchild);
PostOrder(T->rchild);
printf("%d ",T->data);
return 1;
}
int CountLeaf (BiTree T){

if (!T ) return 0;
if (!T->lchild && !T->rchild) return 1;
int m;
int n;
m = CountLeaf( T->lchild);

n = CountLeaf( T->rchild);

return (m+n);

}

void main(){
int a;
BiTree T;
CreateBiTree(T);
printf("先序遍历:");
PreOrder(T);
printf("中序遍历:");
InOrder(T);
printf("后序遍历:");
PostOrder(T);
a=CountLeaf(T);
printf("叶子节点个数:");
printf("%d",a);
}
相似回答