Chain binary tree:
Traversal:
- prologue
- In order
- After the order
Here is a concrete implementation:
1. preorder traversal:
void PreTraverseLTree(struct LTNode *pT)
{
if(pT!=NULL)
{
cout<<pT->data<<'\t';
if(pT->pLchild!=NULL)
PreTraverseLTree(pT->pLchild);
if(pT->pRchild !=NULL)
PreTraverseLTree(pT->pRchild);
}
}
2. preorder:
void InTraverseLTree(struct LTNode *pT)
{
if(pT!=NULL)
{
if(pT->pLchild!=NULL)
InTraverseLTree(pT->pLchild);
cout<<pT->data<<'\t';
if(pT->pRchild !=NULL)
InTraverseLTree(pT->pRchild);
}
}
3. postorder:
void PostTraverseLTree(struct LTNode *pT)
{
if(pT!=NULL)
{
if(pT->pLchild!=NULL)
PostTraverseLTree(pT->pLchild);
if(pT->pRchild !=NULL)
PostTraverseLTree(pT->pRchild);
cout<<pT->data<<'\t';
}
}
------ "source code:
#include<iostream>
#include<malloc.h>
using namespace std;
//结构描述:
struct LTNode
{
char data;
struct LTNode *pLchild;
struct LTNode *pRchild;
};
//初始化:
struct LTNode *CreatLTree()
{
struct LTNode *pA=(struct LTNode *)malloc(sizeof(struct LTNode ));
struct LTNode *pB=(struct LTNode *)malloc(sizeof(struct LTNode ));
struct LTNode *pC=(struct LTNode *)malloc(sizeof(struct LTNode ));
struct LTNode *pD=(struct LTNode *)malloc(sizeof(struct LTNode ));
struct LTNode *pE=(struct LTNode *)malloc(sizeof(struct LTNode ));
pA->data='A';
pB->data='B';
pC->data='C';
pD->data='D';
pE->data='E';
pA->pLchild =pB;
pA->pRchild=pC;
pB->pLchild=pB->pRchild=NULL;
pC->pLchild=pD;
pC->pRchild=NULL;
pD->pLchild =NULL;
pD->pRchild=pE;
pE->pLchild=pE->pRchild=NULL;
return pA;
};
//1.前序遍历:
void PreTraverseLTree(struct LTNode *pT)
{
if(pT!=NULL)
{
cout<<pT->data<<'\t';
if(pT->pLchild!=NULL)
PreTraverseLTree(pT->pLchild);
if(pT->pRchild !=NULL)
PreTraverseLTree(pT->pRchild);
}
}
//2.中序遍历:
void InTraverseLTree(struct LTNode *pT)
{
if(pT!=NULL)
{
if(pT->pLchild!=NULL)
InTraverseLTree(pT->pLchild);
cout<<pT->data<<'\t';
if(pT->pRchild !=NULL)
InTraverseLTree(pT->pRchild);
}
}
//3.后序遍历:
void PostTraverseLTree(struct LTNode *pT)
{
if(pT!=NULL)
{
if(pT->pLchild!=NULL)
PostTraverseLTree(pT->pLchild);
if(pT->pRchild !=NULL)
PostTraverseLTree(pT->pRchild);
cout<<pT->data<<'\t';
}
}
int main()
{
struct LTNode *pT=CreatLTree();
cout<<"前序遍历:"<<endl;
PreTraverseLTree(pT);
cout<<endl;
cout<<"中序遍历:"<<endl;
InTraverseLTree(pT);
cout<<endl;
cout<<"后序遍历:"<<endl;
PostTraverseLTree(pT);
cout<<endl;
return 0;
}
The most common tree structure is a binary tree, because of its unique structure and are stored in the future, many
are involved in algorithm design, a wide range of applications. Here to tell you that the most basic binary tree traversal of the chain, in the future there will be a lot of development and application, those are relatively complex content. As well as when traversing the tree, we generally use the recursive algorithm (though less efficient, but simple design ah!).