-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinvertBinaryTree2.c
92 lines (80 loc) · 1.75 KB
/
invertBinaryTree2.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdio.h>
#include <stdlib.h>
typedef struct node node;
struct node {
int data;
node *l, *r;
};
typedef struct list list;
struct list {
node *node;
list *next;
};
node *invert(node *root)
{
if (root == NULL)
return NULL;
node *temp = root->r;
root->r = invert(root->l);
root->l = invert(temp);
return root;
}
list *push(list *back, node *data)
{
if (data == NULL)
return back;
list *result;
result = (list *) malloc(sizeof(list));
result->node = data;
result->next = NULL;
if (back == NULL)
return result;
else
return back->next = result;
}
list *pop(list *front)
{
list *newFront = front->next;
free(front);
return newFront;
}
void printTree(node *root)
{
list *back = push(NULL, root);
list *front = back;
int i = 0, j = 1;
while (front != NULL) {
root = front->node;
back = push(back, root->l);
back = push(back, root->r);
printf("%3d", root->data);
front = pop(front);
if (++i >= j) {
j = (j + 1) * 2 - 1;
putchar('\n');
}
}
}
int main(int argc, char *argv[])
{
int deep, i;
printf("how is deep?");
scanf("%d", &deep);
//sum = 2^(k+1)-1
int size = (1 << deep) - 1;
printf("size is %d\n", size);
node *tree = (node *) malloc(sizeof(node) * size);
for (i = 0; i < size; i++) {
scanf("%d", &tree[i].data);
int left = 2 * i + 1;
if (left + 1 < size)
tree[i].r = (tree[i].l = tree + left) + 1;
else
tree[i].l = tree[i].r = NULL;
}
printTree(tree);
printf("invert\n");
tree = invert(tree);
printTree(tree);
return 0;
}