以数组方式建立二叉树

sicily 1156
//结点以0到1000标识,存储在数组tree[1001]中,这样就可以不用按遍历或按层遍历的方法来建立二叉树了,随时都可以插入一结点
#include<iostream>
#include
<stack>
#include
<memory.h>
using namespace std;
int isroot[1001];
bool had[1001];
struct node
{
char c;
int l;int r;
}tree[
1001];
void init()
{
for (int i=0;i<=1000;i++)
tree[i].l
=tree[i].r=0;
memset(isroot,
0,sizeof(isroot));
memset(had,
false,sizeof(had));
}
void addnode(int ii,char cc,int ll,int rr) //满足had[ii]==false&&isroot[ii]即为根结点
{
tree[ii].c
=cc;isroot[ii]=1;
if(ll)
{
tree[ii].l
=ll;isroot[ll]=1;had[ll]=true;
}
if(rr)
{
tree[ii].r
=rr;isroot[rr]=1;had[rr]=true;
}

}
void preorder(int i)
{
//printf("%c",tree[i].c);
//if(tree[i].l)preorder(tree[i].l);
//if(tree[i].r)preorder(tree[i].r);
stack<int> content;int t; //非递归遍历
content.push(i);
while (!content.empty())
{
t
=content.top();
content.pop();
printf(
"%c",tree[t].c);
if(tree[t].r)content.push(tree[t].r);
if(tree[t].l)content.push(tree[t].l);
}
}
int main()
{
int n,i,l,r,j;char c;
while(scanf("%d",&n)!=EOF)
{
init();
for( j=1;j<=n;j++)
{
cin
>>i>>c>>l>>r;
addnode(i,c,l,r);
}
for (j=0;j<=1000;j++)
if(isroot[j]&&!had[j])break;
preorder(j);
printf(
"\n");
}
return 0;
}

  

sicily 1935
#include <iostream>
#include
<string>
#include
<deque>
using namespace std;
string str1,str2;
int n;
struct Node
{
char ch;
Node
*left,*right;
Node()
{
left
=right=NULL;
}
}node[
5000];
Node
* built(int s1,int t1,int s2,int t2)
{
int m=n++; //这里要另外声明变量
node[m].ch=str1[s1];
int mid=str2.find(str1[s1]);
if(s2<mid)
node[m].left
=built(s1+1,s1+mid-s2,s2,mid-1);
if(t2>mid)
node[m].right
=built(s1+mid-s2+1,t1,mid+1,t2);
return &node[m];
}
void bfs(Node *root)
{
deque
<Node*> col;
col.push_back(root);
while(!col.empty())
{
Node
*temp=col.front();
col.pop_front();
cout
<<temp->ch;
if(temp->left!=NULL)
{
col.push_back(temp
->left);
temp
->left=NULL; //修改元素要用指针传递,这样就不必每次都memset
}
if(temp->right!=NULL)
{
col.push_back(temp
->right);
temp
->right=NULL;
}
}
cout
<<endl;
}
int main()
{
int t;
cin
>>t;
while(t--)
{
cin
>>str1>>str2;
n
=0;
Node
*root=built(0,str1.size()-1,0,str2.size()-1);
bfs(root);
}
return 0;
}

  

posted on 2011-08-24 21:15  sysu_mjc  阅读(299)  评论(0编辑  收藏  举报

导航