hdu-5444(简单建树和遍历)

来源:互联网 发布:windows一直在准备配置 编辑:程序博客网 时间:2024/06/04 12:02

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5444

题意:树为二叉树,输入n个数的第一个数为根节点,第二个数和这个根节点比较大小,假如大于当前根节点的值,就往右边的节点走,小于往左边的节点走。直到当前节点的左子树节点为空或右子树节点为空,这个值就确定了位置,不然一直循环下去比较(结合代码理解)。重点内容

代码:

#include <iostream>#include <stdio.h>#include <vector>#include <queue>using namespace std;const int maxn = 1000+5;int T,n,a[maxn],q,x[maxn];struct Node{    int v;    Node *left,*right;    Node():left(NULL),right(NULL) {}};Node* newnode(){    return new Node();}Node* root;void addnode(int x)//建树{    Node* u=root;    while(1)    {        if(x>u->v)        {            if(u->left==NULL)            {                u->left=newnode();//特别要注意这里,要先开辟空间,再赋值u=u->left。                u=u->left;                u->v=x;                return ;            }            else                u=u->left;        }        else        {            if(u->right==NULL)            {                u->right=newnode();                u=u->right;                u->v=x;                return;            }            u=u->right;        }    }    return;}void ans(int x)//遍历输出答案{    Node* u=root;    while(u->v!=x)    {        if(x>u->v)        {            u=u->left;            printf("W");        }        else        {            u=u->right;            printf("E");        }    }}int main(){    scanf("%d",&T);    while(T--)    {        root = newnode();        scanf("%d",&n);        for(int i=0; i<n; i++)        {            scanf("%d",&a[i]);            if(i!=0)                addnode(a[i]);            else            {                root->v=a[i];            }        }        scanf("%d",&q);        for(int i=0; i<q; i++)        {            scanf("%d",&x[i]);            if(x[i]==root->v)                printf("\n");            else            {                ans(x[i]);                printf("\n");            }        }    }    return 0;}