二叉树左右子树交换(C++)

递归:
void exchange(BTree *rt){
 BTree *temp = NULL;
 if(rt->lchild == NULL && rt->rchild == NULL)
        return;
 else{
       temp = rt->lchild;
       rt->lchild = rt->rchild;
       rt->rchild = temp;
 }
 if(rt->lchild)
      exchange(rt->lchild);
 if(rt->rchild)
      exchange(rt->rchild);
}

非递归:
Stack是一个定义好的通用堆栈类型,支持初始化/进站/出战等操作
int Exchange(BiTree *T)
{
  Stack s;
  BiTree *p;
  InitStack(s);
  p=T;
  while(p||!StackEmpty(s)){
    if(p){
      push(s,p);
      p->Lchild;
    }
    else{
      pop(s,p);
      t=p->Rchild;
      p->Rchild=p->Lchild;
      p->Lchild=t;
      p-=->Lchild;
    }
  }
return 1;
}
posted @ 2011-04-21 22:30  Together,  阅读(5176)  评论(0编辑  收藏  举报