uva 699

uva 699

這個題應該是我在uva上面做的第一個關於二叉樹的題,直接一把通過,挺爽的。

思路就是用一個數組,在訪問根節點時將數組的下標傳爲1000,然後每次訪問左子樹,將下標減去1。訪問右子樹,將數組下標加上1.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Tnode{
    int value;
    struct Tnode *left, *right;
}Node;
int fall[2000];
int max=0;
int CreateNode(Node * root,int index){
    int input;
    scanf("%d",&input);
    if(input!=-1){
        fall[index]+=input;
        if(index>max)
            max=index;
        root=(Node *)malloc(sizeof(Node));
        root->value=input;
        root->left=root->right=NULL;
        CreateNode(root->left,index-1);
        CreateNode(root->right,index+1);
    }
    if(input==-1 && index==1000)
        return 0;
    return 1;
}
int main(){
    int input,i,j=1,ret;
    Node * root;
    memset(fall,0,sizeof(fall));
    while(ret=(CreateNode(root,1000))!=0){
        getchar();
        for(i=0;i<max;i++)
            if(fall[i]!=0)
                break;
        printf("Case %d:\n",j);
        for(;i<=max;i++)
            if(i!=max)
                printf("%d ",fall[i]);
            else
                printf("%d\n\n",fall[i]);
        memset(fall,0,sizeof(fall));
        j++;
        max=0;
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章