给点前序序列
abc##de#g##f### #表示空树
数组前序递归建树
#include<stdio.h>
#include<stdlib.h>
const int N1=1e8+5;
const int N2=1e2+5;
int pos,len,t;
char tree[N1];
char str[N2];
void create(int pos)//建立二叉树
{
char c = str[t++];
if(c == '#')//若是‘#’,说明该节点为空返回上一级节点
return;
tree[pos] = c;//若不是‘#’,为本节点赋值
create(pos*2);//递归创建左子树
create(pos*2+1);//递归创建右子树
}
void traverse(int root)//中序遍历二叉树
{
if(tree[root]==0)//如果该节点为0,说明该节点为空,返回上一级
return;
traverse(2*root);//先遍历左子树
printf("%c ",tree[root]);//遍历完左子树后,访问本节点
traverse(2*root+1);//再遍历右子树
}
int main()
{
while(scanf("%s",str)!=EOF)
{
t=0;
create(1);
traverse(1);
printf("\n");
}
}
指针递归建树
#include<bits/stdc++.h>
using namespace std;
string s;
int pos=0;
typedef struct tree_node
{
char val;
struct tree_node * l;
struct tree_node *r;
tree_node(char c):val(c),l(NULL),r(NULL){};
} tree_node;
tree_node *build()
{
char c=s[pos++];
if(c=='#')
{
return NULL;
}
tree_node * root=new tree_node(c);
root->l=build();
root->r=build();
return root;
}
void mid(tree_node *root)
{
if(root!=NULL)
{
mid(root->l);
cout<<root->val<<" ";
mid(root->r);
}
return ;
}
int main()
{
cin>>s;
tree_node* root=build();
mid(root);
return 0;
}
二叉搜索树
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
int val;
int l;
int r;
}node;
node v[1000004];
int num;
void build(int root,int val)
{
if(v[root].val==0)
{
v[root].val=val;
return ;
}
if(v[root].val==val)
{
return;
}
if(val<v[root].val)
{
if(v[root].l==0)
{
v[root].l=++num;
}
build(v[root].l,val);
}
else
{
if(v[root].r==0)
{
v[root].r=++num;
}
build(v[root].r,val);
}
return ;
}
void pre(int root)
{
if(v[root].val!=0)
{
cout<<v[root].val<<" ";
pre(v[root].l);
pre(v[root].r);
}
return ;
}
void mid(int root)
{
if(v[root].val!=0)
{
mid(v[root].l);
cout<<v[root].val<<" ";
mid(v[root].r);
}
return ;
}
void hou(int root)
{
if(v[root].val!=0)
{
hou(v[root].l);
hou(v[root].r);
cout<<v[root].val<<" ";
}
return ;
}
int a[1000005];
int main()
{
int n;
num=1;
cin>>n;
v[1].val=a[1];
for(int i=1;i<=n;i++)
{
cin>>a[i];
build(1,a[i]);
}
pre(1);
cout<<endl;
mid(1);
cout<<endl;
hou(1);
//cout<<endl;
}