您的位置:首页 > 其它

算法竞赛入门经典 第二版 习题6-2 S树 S-Trees uva712

2017-04-10 19:37 429 查看
题目:https://vjudge.net/problem/UVA-712

二叉树相关,只要题意能理解清楚就不难。

大致题意:给出一棵满二叉树,每层的(包括根节点)按顺序被编号为“x+数字”,之后的01字符串输入末端节点(叶子)从左到右权值。给出一些查询,0表示遇到节点向求左走,1表示遇到节点向右走,每个查询到达的叶子的值。如查询001表示遇到编号为x1节点向左走,遇到编号为x2的节点向左走,遇到编号为x3的节点向右走,最终到达叶子,返回对应叶子的值(0或1)。

思路:建树,每节点记下编号,用循环查询输出即可。

代码:C++

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

struct Node
{
int value;
Node *left;
Node *right;
Node(): left(NULL), right(NULL) {}
Node(int v): value(v), left(NULL), right(NULL) {}
};

Node *root;
int n;
int order[10];
string leaves;

void build(Node *&nowroot, int depth, int &cnt)
{
if(depth!=n)
{
nowroot = new Node(order[depth]);
build(nowroot->left, depth+1, cnt);
build(nowroot->right, depth+1, cnt);
}
else
{
nowroot = new Node(int(leaves[cnt++]-'0'));
}
}

int main()
{
int T = 1;
while(scanf("%d", &n) && n)
{
for(int i=0; i<n; i++)
{
scanf("%*c%*c%d", &order[i]);
}
cin >> leaves;
int cnt = 0;
build(root, 0, cnt);
printf("S-Tree #%d:\n", T++);
int m;
cin >> m;
while(m--)
{
string inquire;
cin >> inquire;
Node *t = root;
for(int i=0; i<n; i++)
{
t = bool(inquire[t->value-1]-'0')?t->right:t->left;
}
printf("%d", t->value);
}
cout << endl << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐