OJ测试交换二叉树的左右结点

#include<iostream>
#include<stack> 
#include<queue> 
#define OK 1
#define maxsize 100
using namespace std;

//定义一棵树的结构体包括根结点、左孩子,右孩子(字符树)
typedef struct Tnode {
	char data;
	string combine_data;	//结点数据域(数值,可大于9),用于树的表达式求值
	struct Tnode* lchild, * rchild;
}*Btree;

void PreOrder_recursion(Btree T);
//前序遍历创建树,使用char数组
void  CreateTree(Btree& T, char s[], int& i) {
	if (s[i] == '0') {
		T = NULL;
	}
	else {
		T = new Tnode;
		T->data = s[i];
		CreateTree(T->lchild, s, ++i);  //递归构建左子树
		CreateTree(T->rchild, s, ++i);  //递归构建右子树
	}
}

void PreOrder_recursion(Btree T) {
	if (T != NULL) {
		cout << T->data;
		PreOrder_recursion(T->lchild);
		PreOrder_recursion(T->rchild);
	}
}

//交换树的左右孩子
void swap(Btree& T1, Btree& T2)
{
	Btree t;
	t = T1;
	T1 = T2;
	T2 = t;
}

void Node_Swap(Btree& T)
{
	if (T)
	{
		if (T->rchild != NULL && T->lchild != NULL)
		{
			swap(T->rchild, T->lchild);
		}
		else if (T->lchild != NULL && T->rchild == NULL)
		{
			T->rchild = T->lchild;
			T->lchild = NULL;
		}
		else if (T->lchild == NULL && T->rchild != NULL)
		{
			T->lchild = T->rchild;
			T->rchild = NULL;
		}
		else
		{
			;//空操作
		}
		Node_Swap(T->lchild);
		Node_Swap(T->rchild);
	}
	else
	{
		;//空操作
	}
}

int main()
{
	char s[maxsize];
	while (cin >> s && s[0] != '0')
	{
		int i = -1;
		int zero = 0, one = 0, two = 0;
		Btree T = NULL;
		CreateTree(T, s, ++i);
		
		PreOrder_recursion(T); cout << endl;
		Node_Swap(T);
	
		PreOrder_recursion(T);
		cout << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值