L2-011. 玩转二叉树
直接按照层次遍历找就好了,递归,先生成右子树就好啦!!!!
接着上代码吧。。。。
没想到节点值给的比较大点
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1000;
typedef struct node{
int l, r;
};
node a[maxn];
int b[maxn], q[maxn];
int build(int la, int ra, int lb, int rb) { //la, ra表示中序遍历,lb, rb表示前序遍历;
if(la > ra) return 0;
int rt = q[lb], p1, p2;
p1 = la;
while(b[p1] != rt) p1++;
p2 = p1 - la;
a[rt].r = build(la, p1 - 1, lb + 1, lb + p2);
a[rt].l = build(p1 + 1, ra, lb + p2 + 1, rb);
return rt;
}
void bfs(int x) {
queue<int> q;
vector<int> v;
q.push(x);
while(!q.empty()) {
int w = q.front();
q.pop();
if(w == 0) break;
v.push_back(w);
if(a[w].l != 0) q.push(a[w].l);
if(a[w].r != 0) q.push(a[w].r);
}
int len = v.size();
cout << v[0] ;
for(int i = 1; i < len; i++)
cout << " " << v[i];
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++) scanf("%d", &b[i]);
for(int i = 0; i < n; i++) scanf("%d", &q[i]);
build(0, n-1, 0, n-1);
int root = q[0];
bfs(root);
return 0;
}