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

来源:互联网 发布:电视机电视直播软件 编辑:程序博客网 时间:2024/06/01 09:49

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

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

#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;}


0 0
原创粉丝点击