层序遍历,中序遍历,数组模拟二叉树
以下是来自 Max Howell @twitter 的内容:谷歌:我们的百分之九十的工程师都使用你编写的软件,但是你连在白板上反转二叉树都做不到,还是滚吧。现在,请你证明你会反转二叉树。
输入格式
第一行包含一个整数 N,表示树的结点数量。所有结点编号从 0 到 N−1。
接下来 N 行,每行对应一个 0∼N−1 的结点,给出该结点的左右子结点的编号,如果该结点的某个子结点不存在,则用 − 表示。
输出格式
输出反转后二叉树的层序遍历序列和中序遍历序列,每个序列占一行。相邻数字之间用空格隔开,末尾不得有多余空格。
数据范围
1≤N≤10
输入样例:
8
1 -
0 -
2 7
5 -
4 6
输出样例:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
#include<iostream>
#include<cstring>
using namespace std;
const int N=15;
int l[N],r[N],root,n;
int h[N],hh,tt; //队列
bool fa[N];
void bfs(int u)
{
h[hh++]=u;
while(hh>tt)
{
int k=h[tt++];
cout<<k<<" ";
if(l[k]!=-1) h[hh++]=l[k];
if(r[k]!=-1) h[hh++]=r[k];
}
}
void dfs(int u)
{
if(u==-1) return;
dfs(l[u]);
cout<<u<<" ";
dfs(r[u]);
}
int main()
{
cin>>n;
memset(l,-1,sizeof l);
memset(r,-1,sizeof r);
for(int i=0;i<n;i++)
{
string a,b;
cin>>a>>b;
if(a!="-") r[i]=stoi(a),fa[r[i]]=true;
if(b!="-") l[i]=stoi(b),fa[l[i]]=true;
}
while(fa[root]) root++;
bfs(root);
cout<<endl;
dfs(root);
return 0;
}