-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathPreOrder.c
68 lines (57 loc) · 1.38 KB
/
PreOrder.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Your task is to implement the following function :
// void preorder(TreeNode*)
// You will be working with the following structure :
// struct TreeNode {
// int x;
// struct TreeNode* L;
// struct TreeNode* R;
// }
// You may only edit the BODY of the code, leaving the HEAD and the TAIL as it is.
// Sample Input 0
// 7
// 4 2 1 3 6 7 5
// Sample Output 0
// 4 2 1 3 6 5 7
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#define scan(x) scanf(" %d", &x)
struct TreeNode {
int x;
struct TreeNode* L;
struct TreeNode* R;
};
typedef struct TreeNode TreeNode;
TreeNode* newNode(int _x) {
TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode));
node->x = _x;
node->L = node->R = NULL;
return node;
}
TreeNode* insert(TreeNode* node, int val) {
if (node == NULL) return newNode(val);
if (val <= node->x) node->L = insert(node->L, val);
else node->R = insert(node->R, val);
return node;
}
/*******************************************************************/
void preorder(TreeNode* Root)
{
if(Root==NULL)
return;
printf("%d ", Root->x);
preorder(Root->L);
preorder(Root->R);
}
/*******************************************************************/
int main() {
int val, N; scan(N);
TreeNode* Root = NULL;
for (int i = 1; i <= N; i++) {
scan(val);
Root = insert(Root, val);
}
preorder(Root);
}