-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinOrder.c
29 lines (26 loc) · 979 Bytes
/
inOrder.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "inOrder.h"
int *in_order(tree_t *tree){
if (tree == NULL) return NULL;
int *ret = malloc(tree->number_elements * sizeof(int));
if (ret == NULL) return NULL;
int index = 0; // number of elements already copied to the response array
if (tree->left != NULL){
int *temp = in_order(tree->left); // result for left sub-tree
if (temp == NULL) return NULL; // error in malloc
memcpy(ret, temp, tree->left->number_elements * sizeof(int));
free(temp);
index += tree->left->number_elements;
}
*(ret+index) = tree->value;
index++;
if (tree->right != NULL){
int *temp = in_order(tree->right); // result for right sub-tree
if (temp == NULL) return NULL; // error in malloc
memcpy(ret+index, temp, tree->right->number_elements * sizeof(int));
free(temp);
}
return ret;
}