pangfengliu / programmingtasks

programming tasks from my courses
67 stars 17 forks source link

Construct a Binary Search Tree #360

Open littlehug opened 5 years ago

littlehug commented 5 years ago

Write a function to construct a binary search tree according to the weight or the height.

Task Description

You are given N students’ names, heights and weight. You need to construct a binary search tree according to the compiler flag.

For example, we are given students’ informations as follows:

Name Height Weight
John 175 70
Tom 160 80
Mary 165 45

If we compile with flag -DHEIGHT, we need to construct the binary search tree according to the students’ heights as follows: figure

And, If we compile with flag -DWEIGHT, we need to construct the binary search tree according to the students’ weights as follows: figure

Note

It is guaranteed that all the heights and all the weights are different. Exactly one of the HEIGHT and WEIGHT flag will be defined. All pointers that do not link to any node must be set to NULL.

Please construct the binary search tree in the function, Node *ConstructBSTree( … ), then return the pointer of the root. The main program and the prototype of function ConstructBSTree are as followed:

/* construct.h */
#ifndef CONSTRUCT
#define CONSTRUCT
typedef struct Node{
    char name[16];
    int height;
    int weight;
    struct Node *left, *right;
} Node;

Node *ConstructBSTree(int N, char name[][16], int height[], int weight[]);
#endif
/* main.c */
#include <stdio.h>
#include "construct.h"

#define MAXN 1024
char name[MAXN][16];
int height[MAXN];
int weight[MAXN];

void PrintBSTree( Node *root ){
    if (root == NULL)
        return;
    printf("%s\n", root->name);
    PrintBSTree(root->left);
    PrintBSTree(root->right);
    return;
}

int main(){
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++)
        scanf("%s %d %d", name[i], &height[i], &weight[i]);

    Node *tree = ConstructBSTree( N, name, height, weight );

    PrintBSTree( tree );
    return 0;
}

Compile

gcc -std=c99 -O2 -DHEIGHT main.c construct.c -o test1
gcc -std=c99 -O2 -DWEIGHT main.c construct.c -o test2

Subtask

Output Format

Print all the names of nodes in the binary search tree by pre-ordering, and each node in a line.

Compile with flag -DHEIGHT

Sample Input 1

3
John 175 70
Tom 160 80
Mary 165 45

Sample Output 1

John
Tom
Mary

Sample Input 2

3
John 175 70
Tom 160 80
Mary 165 45

Sample Output 2

John
Mary
Tom