二叉树交换左右子树

#include<stdio.h>
#include<malloc.h>
typedef struct Node{
 
 int data;
 struct Node* LChild;
 struct Node* RChild;
}Tree;

void createTree(Tree **T)
{
 int data = 1;
 scanf("%d",&data);
 if ( data != 0)
 {
  
  
  *T = (Tree *)malloc(sizeof(Tree));
  (*T)->data = data;
  (*T)->LChild = NULL;
  (*T)->RChild = NULL;
  createTree(&(*T)->LChild);
  createTree(&(*T)->RChild);
 }
 
}

void printTree(Tree *T)
{
 if ( T!=NULL)
 {
  printf("%d ",T->data);
  printTree(T->LChild);
  printTree(T->RChild);
 }
 
}

Tree * exchange_rootFirlst(Tree* T)   //先序遍历
{
 if(T!=NULL)
  if(T->LChild!=NULL||T->RChild!=NULL)
  {
   Tree *p,*q;
   p = exchange_rootFirlst(T->LChild);
   q = exchange_rootFirlst(T->RChild);
   T->LChild = q;
   T->RChild = p;
  }
  
  return T;
  
}

void exchange_rootLast(Tree* T)    // 后序遍历
{
 if(T!=NULL)
  if(T->LChild!=NULL||T->RChild!=NULL)
  {
   Tree *p,*q;
   q = T->RChild;
   p = T->LChild;
            T->LChild = q;
   T->RChild = p;
   exchange_rootLast(T->LChild);
   exchange_rootLast(T->RChild);
   
  }
  
  
  
}

Tree * exchange_rootMiddle(Tree* T)     //类似于中序遍历
{
 if(T!=NULL)
  if(T->LChild!=NULL||T->RChild!=NULL)
  {
   Tree *p,*q;
   p = exchange_rootMiddle(T->LChild);
           
   q = T->RChild;
   T->RChild = p;
   T->LChild = q;
   q = exchange_rootMiddle(T->RChild);
   
  }
  
  return T;
  
}

void main()
{
 Tree *T ;
 createTree(&T);
 printTree(T);
 printf("\n");
 exchange_rootFirlst(T);
 printTree(T);
 printf("\n");
 exchange_rootLast(T);
 printTree(T);
 printf("\n");
 exchange_rootMiddle(T);
 printTree(T);
 printf("\n");
 
}
 

交换二叉树的左右子树可采用先序遍历,中序遍历,后序遍历完成。先序与后序不需要考虑太多,简单交换即可。中序遍历要考虑到,若左子树已经交换过了,那么左右一交换,原来的左变为右了,原来的右子树变为左子树,而新的左子树是没有进行交换过的。

  • 7
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值