二叉树回顾(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;
}
相关文章推荐
- Java native interface(一)
- ueditor 上传文件到ftp java
- 非ssh命令的远端服务器的操作方法
- Linux系统下取IP地址的几种方法
- git clone 远程分支
- mybatis-generator插件命令
- iOS开发~FMDB的使用
- Java设计模式--单例模式
- Unity集成Leap Motion
- Android 性能优化
- Android实用方法 — onActivityResult
- com.android.support:appcompat-v7错误解决方法
- Android性能优化之内存篇
- 【Debug Assertion Failed!Expression:_pFirstBlock == pHead vs2013编程错误】
- SharePoint2013 IT Professional - Public View& Personal View
- 企业支付宝账号开发接口教程--JAVA-UTF-8
- LeetCode 190 Reverse Bits
- JVM的垃圾收集器
- 1.1 smtp协议及其扩展
- Android——ImageView的scaleType属性与adjustViewBounds属性 (转)二