1622-构造二叉树

(http://acm.hdu.edu.cn/showproblem.php?pid=1622)

#include <algorithm>  
#include <iostream>  
#include <cstdlib>  
#include <cstring>  
#include <cstdio>  
#include <cmath>  
#include<conio.h> 
using namespace std;  

typedef struct tnode  
{  
   int  V;  
   tnode* L;  
   tnode* R;  
}tree;  

tree node[300];  
tree* root;  
int tree_size,complete;  

int test(tree* root)  //检测树的完整性 
{  
    if(!root->V) return 0;  
    int ans = 0;  
    if (!root->L || test(root->L)) //要么没有左孩子,要么有左孩子且左子树完整 
       ans++; //或语句:第一个条件符合则不判断第二个 
    if (!root->R || test(root->R)) //要么没有右孩子,要么有右孩子且右子树完整
       ans++;  
    return ans == 2;  
}  

void madetree(tree *root, char* str, int v)  
{  
    if (*str == 'R') {  
       if (!root->R)  
           root->R = &node[++tree_size]; 
//如果当前节点没有右指针,则给一个右指针,因为下一条madetree需要一个右指针 ,这样才能继续建树 
       madetree(root->R, str+1, v);  
    }else if (*str == 'L') {  
        if (!root->L)  
          root->L = &node[++tree_size]; 
//如果当前节点没有左指针,则给一个左指针,因为下一条madetree需要一个左指针 ,这样才能继续建树 
        madetree(root->L, str+1, v);  
    }else {  
        if (root->V)  
            complete = 0;  
        root->V = v;//给当前节点数据域赋值  
    }  
}  

tree* Q[300];  
void output(tree *root)  //层序遍历输出 
{  
    int behind = 0,front = 0;//一个指针在前,一个指针在后  
    Q[front++] = root;  
    printf("%d",root->V);  
    while(behind < front) {  
        tree* now = Q[behind++];  
        if (now->L) {  
            printf(" %d",now->L->V);  
            Q[front++] = now->L;  
        }  
        if (now->R) {  
           printf(" %d",now->R->V);  
           Q[front++] = now->R;  
        }  
    }printf("\n");  
}  

int main()  
{  
    char buf[256],leaf[256];  
    int value;  
    complete = 1;  
    root = &node[tree_size = 0];  
        while (~scanf("%s",buf)) {  
       if (!strcmp(buf,"()")) {  
           if (!complete || !test(root))  
               printf("not complete\n");  
           else output(root);  

           memset(node, 0, sizeof(node));  
           root = &node[tree_size = 0];  
           complete = 1;  
        }else {  
            sscanf(buf,"(%d,%s)",&value,leaf);  
            madetree(root, leaf, value);  
       }  
    }  
    getch(); 
    return 0;  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值