#include<iostream>
using namespace std;
typedef struct treeNode
{
char data;
struct treeNode*LChild;
struct treeNode*RChild;
}TREE,*LPTREE;
//别名中lp一般表示是指针别名
LPTREE createNode(char data)
{
LPTREE newNode=(LPTREE)malloc(sizeof(TREE));
newNode->data=data;
newNode->LChild=NULL;
newNode->RChild=NULL;
return newNode;
}
//没有规律的树
void insertNode(LPTREE parentNode,LPTREE LChild,LPTREE RChild)
{
parentNode->LChild=LChild;
parentNode->RChild=RChild;
}
//打印当前节点中的元素
void printCurNodeData(LPTREE curData)
{
cout<<curData->data;
}
//递归法:领悟
//先序:根 左 右
void preOrder(LPTREE root)
{
if(root!=NULL)
{
printCurNodeData(root); //根
preOrder(root->LChild); //左
preOrder(root->RChild); //右
}
}
//中序: 左 根 右
void midOrder(LPTREE root)
{
if(root!=NULL)
{
midOrder(root->LChild); //左
printCurNodeData(root); //根
midOrder(root->RChild); //右
}
}
//后序: 左 右 根
void lastOrder(LPTREE root)
{
if(root!=NULL)
{
lastOrder(root->LChild); //左
lastOrder(root->RChild); //右
printCurNodeData(root); //根
}
}
int main()
{
//死板的创建过程,无实际作用
LPTREE A=createNode('A');
LPTREE B=createNode('B');
LPTREE C=createNode('C');
LPTREE D=createNode('D');
LPTREE E=createNode('E');
LPTREE F=createNode('F');
LPTREE G=createNode('G');
insertNode(A, B, C);
insertNode(B,D,NULL);
insertNode(D, NULL,G);
insertNode(C,E,F);
cout<<"先序遍历:"<<endl;
preOrder(A);
cout<<endl;
cout<<"中序遍历:"<<endl;
midOrder(A);
cout<<endl;
cout<<"后序遍历:"<<endl;
lastOrder(A);
cout<<endl;
}
对于这种递归的方法,其实是较难理解的,初学者可能看到有点不懂,我建议大家可以仅以三个节点为例子进行分析,可以更好的帮助您的理解