之前建树都是用数组存储,这回用指针
#include<bits/stdc++.h>
#define ll long long
#define inf 999999999
using namespace std;
int qian[50];
int zhong[50];
vector<int> v;
struct node{
int data;
node* left; //java里面的"指针"就是直接不加星号即可
node* right;
};
node* build(int l1,int r1,int l2,int r2)
{
if(l1>r1)
return NULL; //结束时就返回空
node* root=new node; //开一个node,用来存储根节点,左儿子,右儿子
root->data=qian[l1];
int p=l2;
while(zhong[p]!=root->data)
p++;
int cnt=p-l2;
root->left=build(l1+1,l1+cnt,l2,l2+cnt-1);
root->right=build(l1+cnt+1,r1,p+1,r2);
return root;
}
void houshow(node* root)
{
if(root==NULL)
return;
houshow(root->left);
houshow(root->right);
v.push_back(root->data);
}
int main()
{
int n;
cin>>n;
stack<int> s;
string t;
int a,k1=0,k2=0;
for(int i=1;i<=2*n;i++)
{
cin>>t;
if(t=="Push")
{
cin>>a;
qian[k1++]=a;
s.push(a);
}
else
{
zhong[k2++]=s.top();
s.pop();
}
}
node* root=build(0,n-1,0,n-1);
houshow(root);
for(int i=0;i<v.size()-1;i++)
cout<<v[i]<<" ";
cout<<v[v.size()-1]<<endl;
}
求层序遍历
void bfs(node* root)
{
queue<node*> q; //注意这里村的是指针类型
q.push(root);
while(!q.empty())
{
node* u=q.front();
q.pop();
v.push_back(u->data);
if(u->l!=NULL)
q.push(u->l);
if(u->r!=NULL)
q.push(u->r);
}
}
附上用数组的写法:
#include<bits/stdc++.h>
#define ll long long
#define inf 999999999
using namespace std;
int qian[105];
int zhong[105];
struct node{
int left;
int right;
}tree[100005]; //有的题数特别大的话就不能用数组写法
vector<int> v;
int build(int l1,int r1,int l2,int r2)
{
if(l1>r1)
return -1;
int root=qian[l1];
int p=l2;
while(zhong[p]!=root)
p++;
int cnt=p-l2;
tree[root].left=build(l1+1,l1+cnt,l2,l2+cnt-1);
tree[root].right=build(l1+cnt+1,r1,p+1,r2);
return root;
}
void houshow(int root)
{
if(root==-1)
return;
houshow(tree[root].left);
houshow(tree[root].right);
v.push_back(root);
}
int main()
{
int n;
cin>>n;
stack<int> s;
string t;
int a,k1=0,k2=0;
for(int i=1;i<=2*n;i++)
{
cin>>t;
if(t=="Push")
{
cin>>a;
s.push(a);
qian[k1++]=a;
}
else
{
zhong[k2++]=s.top();
s.pop();
}
}
int root=build(0,n-1,0,n-1);
houshow(root);
for(int i=0;i<v.size()-1;i++)
cout<<v[i]<<" ";
cout<<v[v.size()-1]<<endl;
}