主要是自我的总结
前序遍历:根结点->左子树->右子树
中序遍历:左子树->根结点->右子树
后序遍历:左子树->右子树->根结点
二叉树的定义(为了输出好看,定义char类型):
struct binarytree{
char value;
binarytree* leftnode;
binarytree* rightnode;
binarytree(){
value='0';
leftnode=NULL;
rightnode=NULL;
}
};
前序遍历:
void foresearch(binarytree*a)
{
//前序遍历
if(a==NULL)
return;
cout<<a->value;
foresearch(a->leftnode);
foresearch(a->rightnode);
}
中序遍历:
void midsearch(binarytree*a)
{
//中序遍历
if(a==NULL)
return;
midsearch(a->leftnode);
cout<<a->value;
midsearch(a->rightnode);
}
后序遍历:
void backsearch(binarytree*a)
{
//后序遍历
if(a==NULL)
return;
backsearch(a->leftnode);
backsearch(a->rightnode);
cout<<a->value;
}
利用前序序列和中序序列构造二叉树:
void CreateTree(binarytree*a,string preArray,string midArray)
{
//利用前序和中序构造二叉树
if(preArray=="")
return;
binarytree A;
A.value=preArray[0]; //将前序序列的第一个当根节点
int index;
index=midArray.find(A.value);
binarytree B;
binarytree C;
CreateTree(&B,preArray.substr(1,index),midArray.substr(0,index)); //进行分割,创造左子树
CreateTree(&C,preArray.substr(1+index),midArray.substr(1+index)); //进行分割,创造右子树
A.leftnode=&B;
A.rightnode=&C;
return;
}