题意:给一颗满二叉树,只有叶子节点有值。现在从根节点出发,走左儿子记0,走右儿子记1,给出一个路线,求最后到达的叶子节点的值是多少。
思路:按照路线模拟输出即可。如果是一个n层的满二叉树。最底层的第一个节点编号为2^(n-1),一共有2^(n-1)个叶子节点。
将原编号为 2^(n-1) 到 2^n-1的叶子节点的值存到数组[1]到[2^(n-1)]中,按照路线求出叶子编号直接输出即可。
#include <iostream>
#include <cstdio>
using namespace std;
char ans[130];
char temp[50];
int n,m;
int query;
int sum = 0;
int main()
{
while(cin>>n)
{
if ( !n ) break;
sum++;
printf("S-Tree #%d:\n",sum);
getchar();
gets(temp);
int up = 1<<n;
for(int i = 1; i <= up; i++ ) ans[i] = getchar();
cin>>m;
getchar();
for(int i = 1; i <= m; i++ )
{
gets(temp);
int pos = 1;
for(int i = 0; i < n; i++ )
if ( temp[i] == '0' ) pos<<=1;
else pos = pos<<1|1;
cout<<ans[pos - up + 1];
}
puts("");
puts("");
}
return 0;
}