二叉树子树互换
时间:2010-10-21 来源:Sea_Giggs
这个程序是实现二叉树的左右子树互换,可以用递归和非递归实现,在这里,我先用递归实现,递归程序很简单。
/*
* Copyright (c) 2010-~ Dahai
*
* This source code is released for free distribution under the terms of the
* GNU General Public License
*
# Author: Dahai<[email protected]>
* Created Time: 2010年10月21日 星期四 17时00分56秒
* File Name: exchange_subtree.c
*
* Description:
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char c;
struct Node *LChild;
struct Node *RChild;
}BiTNode, *BiTree;
void CreateBiTree(BiTree *bt);
void Exchange(BiTree bt);
void PreOrder(BiTree bt);
void InOrder(BiTree bt);
int main()
{
BiTree bt;
CreateBiTree(&bt);
Exchange(bt);
printf("Exchanged order : \n");
printf("PreOrder is : ");
PreOrder(bt);
printf("\t\tInOrder is : ");
InOrder(bt);
printf("\n");
return 0;
}
void CreateBiTree(BiTree *bt)
{
char ch;
ch = getchar();
if('^' == ch){
*bt = NULL;
}
else {
*bt = (BiTree)malloc(sizeof(BiTNode));
(*bt) -> c = ch;
CreateBiTree(&((*bt) -> LChild));
CreateBiTree(&((*bt) -> RChild));
}
}
void Exchange(BiTree bt)
{
BiTree temp;
if(bt){
Exchange(bt -> LChild);
Exchange(bt -> RChild);
temp = bt -> LChild;
bt -> LChild = bt -> RChild;
bt -> RChild = temp;
}
}
void PreOrder(BiTree bt)
{
if(NULL != bt){
printf("%c", bt -> c);
PreOrder(bt -> LChild);
PreOrder(bt -> RChild);
}
}
void InOrder(BiTree bt)
{
if(NULL != bt){
InOrder(bt -> LChild);
printf("%c", bt -> c);
InOrder(bt -> RChild);
}
}
/*
* Copyright (c) 2010-~ Dahai
*
* This source code is released for free distribution under the terms of the
* GNU General Public License
*
# Author: Dahai<[email protected]>
* Created Time: 2010年10月21日 星期四 17时00分56秒
* File Name: exchange_subtree.c
*
* Description:
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char c;
struct Node *LChild;
struct Node *RChild;
}BiTNode, *BiTree;
void CreateBiTree(BiTree *bt);
void Exchange(BiTree bt);
void PreOrder(BiTree bt);
void InOrder(BiTree bt);
int main()
{
BiTree bt;
CreateBiTree(&bt);
Exchange(bt);
printf("Exchanged order : \n");
printf("PreOrder is : ");
PreOrder(bt);
printf("\t\tInOrder is : ");
InOrder(bt);
printf("\n");
return 0;
}
void CreateBiTree(BiTree *bt)
{
char ch;
ch = getchar();
if('^' == ch){
*bt = NULL;
}
else {
*bt = (BiTree)malloc(sizeof(BiTNode));
(*bt) -> c = ch;
CreateBiTree(&((*bt) -> LChild));
CreateBiTree(&((*bt) -> RChild));
}
}
void Exchange(BiTree bt)
{
BiTree temp;
if(bt){
Exchange(bt -> LChild);
Exchange(bt -> RChild);
temp = bt -> LChild;
bt -> LChild = bt -> RChild;
bt -> RChild = temp;
}
}
void PreOrder(BiTree bt)
{
if(NULL != bt){
printf("%c", bt -> c);
PreOrder(bt -> LChild);
PreOrder(bt -> RChild);
}
}
void InOrder(BiTree bt)
{
if(NULL != bt){
InOrder(bt -> LChild);
printf("%c", bt -> c);
InOrder(bt -> RChild);
}
}
相关阅读 更多 +