您的位置:首页 > 其它

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

2016-03-29 15:59 477 查看

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

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

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: