二叉树

发布于 2018-01-05  35 次阅读


题目链接:uva122

思路:简单二叉树题,无需多说

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <queue>
#define ri(n) scanf("%d",&n)
#define oi(n) printf("%d\n",n)
#define rl(n) scanf("%lld",&n)
#define ol(n) printf("%lld\n",n)
#define rep(i,l,r) for(i=l;i<=r;i++)
#define rep1(i,l,r) for(i=l;i<r;i++)
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int epg=10-8;
const int maxn=1e5+10;
typedef struct tnode
{
    int v;
    tnode l;
    tnode r;
} tree;
tree root,node[maxn];
int tree_size,flag;
void build(tree root,char str,int val)//建立二叉树
{
    if(str=='L')
    {
        if(!root->l)
            root->l=&node[++tree_size];
        build(root->l,str+1,val);
    }
    else if(str=='R')
    {
        if(!root->r)
            root->r=&node[++tree_size];
        build(root->r,str+1,val);
    }
    else
    {
        if(root->v)
            flag=0;   //标记是否有结点被赋值两次
        root->v=val;
    }
}
int check(tree root)//判断是否有结点未被赋值
{
    if(!root->v)
        return 0;
    int ans=0;
    if(!root->l||check(root->l))
        ans++;
    if(!root->r||check(root->r))
        ans++;
    return ans==2;
}
tree t[maxn];
void print(tree root)
{
    int head=0,tail=0;
    t[head++]=root;
    printf("%d",root->v);
    while(tail<head)
    {
        tree *now=t[tail++];
        if(now->l)
        {
            printf(" %d",now->l->v);
            t[head++]=now->l;
        }
        if(now->r)
        {
            printf(" %d",now->r->v);
            t[head++]=now->r;
        }
    }
    printf("\n");
}
int main()
{
    char buf[256],leaf[256];
    int  value;
    flag = 1;
    root = &node[tree_size = 0];
    while (~scanf("%s",buf))
    {
        if (!strcmp(buf,"()"))
        {
            //cout<<root->v<<endl;
            if (!flag || !check(root))
                printf("not complete\n");
            else print(root);
            memset(node, 0, sizeof(node));
            root = &node[tree_size = 0];
            flag = 1;
        }
        else
        {
            sscanf(buf,"(%d,%s",&value,leaf);
            build(root, leaf, value);
        }
    }
    return 0;
}

Comments


愿我如星君如月,夜夜流光相皎洁。