二叉树回顾(1):建立、交换左右子树

二叉树的建立和中序遍历输出、交换左右子树

由数组建立二叉排序树,并使用中序遍历进行输出,交换二叉树的左右子树(递归写法)

#include <iostream>
#include<cstdio>
using namespace std;
struct node
{
	int data;
	node *lchild;
	node *rchild;
};

node* newNode(int x)
{
	node *root=new node;
	root->data=x;
	root->lchild=root->rchild=NULL;
	return root;
}

void insert(node* &root,int x)
{
	if(root==NULL)
	{
		root=newNode(x);
		return;
	}	
	//以下不用新建节点,新建的都是在上面递归边界处 
	if(root->data<=x)
	{
		insert(root->rchild,x);
	}
	else
	{
		insert(root->lchild,x);
	}
}

node* create(int a[],int n)
{
	node* root=NULL;
	for(int i=0;i<n;++i)
	{
		insert(root,a[i]);
	}
	return root;
}

void exchange(node* root)
{
	node* temp;
	if(!root)return;
	exchange(root->lchild);
	exchange(root->rchild);
	temp=root->lchild;
	root->lchild=root->rchild;
	root->rchild=temp;
}

//中序序列输出 
void inorder(node* root)
{
	if(root==NULL)return;
	inorder(root->lchild);
	printf("%d ",root->data);
	inorder(root->rchild);
}
int main()
{
	int i,j;
	int a[]={12,43,13,3,5,1,56,74,10,8};
	int n=sizeof(a)/sizeof(a[0]);
	//由数组建立二叉树 
	node* root=create(a,n);
	printf("before exchange:\n");
	inorder(root);
	//交换左右子树 
	exchange(root);
	printf("\nafter excahnge:\n");
	inorder(root);
	return 0;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值