二叉樹每個結點實現左右孩子(如果存在)的交換,這個思想大概就是判斷一下樹的每個結點是否存在左、右結點,若存在,則直接交換位置
核心代碼如下:
通過遞歸遍歷或者其他的遍歷,在遍歷的同時,進行對結點判斷,是否存在左孩子和右孩子,若存在(至少一個),則進行交換
void Exchange(BiNode<T>*t)
{
if(t->lchild!=NULL)
Exchange(t->lchild);
if(t->rchild!=NULL)
Exchange(t->rchild);
BiNode<T>*pointer;
pointer=t->lchild;
t->lchild=t->rchild;
t->rchild=pointer;
}
完全代碼如下:
#include<string>
#include<iostream>
#include<stack>
using namespace std;
//二叉鏈表表示二叉樹
template<class T>
class BiNode
{
public:
T data;//節點數據
BiNode * lchild;//左孩子
BiNode * rchild;//右孩子
BiNode();
BiNode(T d){ data=d; } //new一個結點的時候就給其數據域賦值
~BiNode(){}
//建樹
void createTree(BiNode<T>* &t, string post,string in) //後序,中序
{
if(post.length()==0)
{
t=NULL;
}
if(post.length()!=0)
{
int dex=post.length()-1; //根結點在後序序列的位置
t=new BiNode<T>(post[dex]); //新建一個根結點
int index=in.find(post[dex]); //查找根結點在中序序列的位置
string lchild_in=in.substr(0, index);
string rchild_in=in.substr(index+1);
string lchild_post=post.substr(0, index);
string rchild_post=post.substr(index,rchild_in.length());
if(t!=NULL)
{
createTree(t->lchild,lchild_post,lchild_in);
createTree(t->rchild,rchild_post,rchild_in);
}
}
}
void Exchange(BiNode<T>*t)
{
if(t->lchild!=NULL)
Exchange(t->lchild);
if(t->rchild!=NULL)
Exchange(t->rchild);
BiNode<T>*pointer;
pointer=t->lchild;
t->lchild=t->rchild;
t->rchild=pointer;
}
void inOrder(BiNode<T> *t)//中序遍歷
{
if(t==NULL)
{
return ;
}
if(t!=NULL)
{
inOrder(t->lchild);
cout<<t->data;
inOrder(t->rchild);
}
}
};
int main()
{
BiNode<char> *t=NULL;
string post="FGDBHECA";
string in="BFDGACEH";
t->createTree(t,post,in);
cout<<"交換前的中序遍歷: "<<endl;
t->inOrder(t);
cout<<endl;
cout<<"交換後的中序遍歷: "<<endl;
t->Exchange(t);
t->inOrder(t);
cout<<endl;
return 0;
}