C++二叉树左右孩子的交换

二叉树每个结点实现左右孩子(如果存在)的交换,这个思想大概就是判断一下树的每个结点是否存在左、右结点,若存在,则直接交换位置

核心代码如下:

通过递归遍历或者其他的遍历,在遍历的同时,进行对结点判断,是否存在左孩子和右孩子,若存在(至少一个),则进行交换

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值