二叉树中所有节点的左右子树相互交换 递归与非递归程序

//将二叉树中所有节点的左右子树相互交换
[cpp]  view plain copy
 
  1. BiNode* Exchange(BiNode* T)  
  2. {  
  3.  BiNode* p;  
  4.  if(NULL==T || (NULL==T->lchild && NULL==T->rchild))  
  5.   return T;  
  6.  p = T->lchild;  
  7.  T->lchild = T->rchild;  
  8.  T->rchild = p;  
  9.  if(T->lchild)  
  10.  {  
  11.   T->lchild = Exchange(T->lchild);  
  12.  }  
  13.  if(T->rchild)  
  14.  {  
  15.   T->rchild = Exchange(T->rchild);  
  16.  }  
  17.  return T;  
  18. }  
 
//将二叉树中所有节点的左右子树相互交换
//不使用递归
[cpp]  view plain copy
 
  1. void NonRecursive_Exchange(BiNode* T)  
  2. {  
  3.  Stack s;  
  4.  BiNode* p;  
  5.  if(NULL==T)  
  6.   return;  
  7.  InitStack(&s);  
  8.  Push(&s,T);  
  9.  while(!isEmpty(&s))  
  10.  {  
  11.   T = Pop(&s);  
  12.   p = T->lchild;  
  13.   T->lchild = T->rchild;  
  14.   T->rchild = p;  
  15.    
  16.   if(T->rchild)  
  17.    Push(&s,T->rchild);  
  18.   if(T->lchild)  
  19.    Push(&s,T->lchild);   
  20.  }   
  21.  DestroyStack(&s);   
  22. }  

猜你喜欢

转载自chriszeng87.iteye.com/blog/2218810