#include<bits/stdc++.h> using namespace std; struct node { int l,r; }nodes[32]; int pre[32],in[32]; int n; int build(int a,int b,int c,int d) { int root=pre[a]; int m=c; while(in[m]!=root) m++; if(m==c) nodes[root].l=-1; else nodes[root].l=build(a+1,a+m-c,c,m-1); if(m==d) nodes[root].r=-1; else nodes[root].r=build(a+m-c+1,b,m+1,d); return root; } void bfs(int root) { if(root==-1) return; queue<int> q; q.push(root); while(!q.empty()) { int m=q.front(); if(m==root) cout<<m; else cout<<" "<<m; if(nodes[m].l!=-1) q.push(nodes[m].l); if(nodes[m].r!=-1) q.push(nodes[m].r); q.pop(); } } void Swap(int root) { int tmp=nodes[root].l; nodes[root].l=nodes[root].r; nodes[root].r=tmp; } void revswap(int root) { if(root==-1) return; revswap(nodes[root].l); revswap(nodes[root].r); Swap(root); } int main() { cin>>n; for(int i=0;i<n;i++) cin>>in[i]; for(int i=0;i<n;i++) cin>>pre[i]; int root=build(0,n-1,0,n-1); revswap(root); bfs(root); return 0; }读一下代码
时间: 2024-03-29 09:42:10 浏览: 13
这是一个二叉树的遍历和操作代码。具体来说,它实现了以下功能:
1. 通过前序遍历序列和中序遍历序列构建二叉树,build函数实现了这个功能。
2. 对二叉树进行广度优先遍历,bfs函数实现了这个功能。
3. 对二叉树进行翻转操作,Swap函数实现了这个功能。
4. 对二叉树进行反转和翻转操作,revswap函数实现了这个功能。
在main函数中,它首先读入了树的节点数n,以及树的前序遍历序列pre和中序遍历序列in。然后通过调用build函数构建了二叉树,接着调用revswap函数进行反转和翻转操作,最后调用bfs函数进行广度优先遍历输出结果。
相关问题
#include <bits/stdc++.h> using namespace std;
这个头文件是C++11标准引入的,它包含了所有标准库中的头文件。使用这个头文件可以方便地在一个地方包含所有需要的头文件,而不需要一个一个地包含。这个头文件通常只在竞赛中使用,因为它不是标准C++头文件,不保证在所有编译器中都能正常工作。
以下是一个使用这个头文件的示例,实现输入4个整数a、b、c、d,将它们倒序输出:
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
cout << d << ' ' << c << ' ' << b << ' ' << a << endl;
return 0;
}
```
#include <bits/stdc++.h> using namespace std
这段代码是一个C++的头文件引用和命名空间的使用示例。具体来说,`#include <bits/stdc++.h>`是一个常用的头文件引用方式,它包含了C++标准库中的所有头文件。而`using namespace std`则是为了使用`std`命名空间中的标准库函数和对象,这样就可以直接使用`cout`、`cin`等标准输入输出流对象,而不需要写`std::cout`、`std::cin`。
这种写法虽然方便,但也存在一些问题。首先,包含了所有的标准库头文件可能会导致编译时间变长。其次,使用了`using namespace std`会将整个`std`命名空间中的所有标识符引入当前作用域,可能会导致命名冲突。因此,在实际开发中,建议根据需要只包含需要的头文件,并使用具体的命名空间来避免潜在的问题。