pangfengliu / programmingtasks

programming tasks from my courses
67 stars 17 forks source link

Sequence to Binary Tree #359

Open littlehug opened 5 years ago

littlehug commented 5 years ago

Write a function to convert an integer sequence to a binary tree.

Task Description

You are given an unsorted sequence of N integers. Each integer value is unique, and it has an index from 0 to N-1. You need to convert the sequence to a binary tree according the preprocessing flag MAXLENGTH. When MAXLENGTH is set as k, the k-th largest integer will be picked as the root of the binary tree. Assume its index is t. All integers with indices less than t will be placed into the left subtree and all integers with indices larger than t will be placed into the right subtree. This recursion then goes on the left and right subtrees. Note that if there are less than k integers in the sequence, the binary tree has a sequence of nodes linked by the left pointer as a linked list. And you link the nodes according their indices in descending order.

For example, the integer sequence is {2, 0, 1, 7, 12, 21, 8, 33} and MAXLENGTH is set as 3. The third largest integer in the sequence is 12, so 12 is picked as root and we partition the sequence into two sequences -- {2, 0, 1, 7} and {21, 8, 33}. Then we recursively find the fourth largest integer from them. After finding 1 for the partition on the left subtree and 8 for the right subtree, all remaining sequences have less than four integers, so we link them as a linked list.The final tree is as follows.

figure

When the integer sequence is {2, 0, 1, 7, 12, 21, 8, 33} and MAXLENGTH is set as 5, the binary tree you construct is as followed.

figure

We define tree node as followed. Note that all pointers that do not link to any node must be set as NULL.

typedef struct node{
    int value;
    struct node*left;
    struct node*right;
}Node;

Please write a function to construct the binary tree. The prototype of the function is as followed.

Node*ConstructTree(int sequence[],int N);

You may use the following main function to test your program.

#include <stdio.h>
#include "construct.h"
#define MAXN 16384

int sequence[MAXN];

void PrintTree( Node *root ){
    if (root == NULL)
        return;
    printf("%d\n", root->value);
    PrintTree(root->left);
    PrintTree(root->right);
    return;
}
int main(){
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++)
        scanf("%d", &sequence[i]);
    Node *tree = ConstructTree( sequence, N );
    PrintTree( tree );
    return 0;
}

The construct.h is as followed.

#ifndef CONSTRUCT
#define CONSTRUCT
typedef struct node{
    int value;
    struct node *left, *right;
} Node;
Node *ConstructTree(int sequence[], int N);
#endif

Subtask