-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path145.binary-tree-postorder-traversal-recursion.c
93 lines (74 loc) · 2.1 KB
/
145.binary-tree-postorder-traversal-recursion.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
92
93
#include <stdio.h>
#include <stdlib.h>
/**
* Definition for a binary tree node.
*/
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void traversalTree(struct TreeNode *node, int *result, int *returnSize)
{
if (node->left != NULL)
{
traversalTree(node->left, result, returnSize);
}
if (node->right != NULL)
{
traversalTree(node->right, result, returnSize);
}
result[(*returnSize)++] = node->val;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int *postorderTraversal(struct TreeNode *root, int *returnSize)
{
*returnSize = 0;
int *result = (int *)malloc(sizeof(int) * 999);
if (root == NULL)
{
return result;
}
traversalTree(root, result, returnSize);
return result;
}
void printArr(int v[], int len)
{
int i;
for (i = 0; i < len; i++)
printf("%d ", v[i]);
printf("\n");
}
int main()
{
struct TreeNode *rootRightLeftRight = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRightLeftRight->val = 4;
rootRightLeftRight->left = rootRightLeftRight->right = NULL;
struct TreeNode *rootRightLeftLeft = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRightLeftLeft->val = 5;
rootRightLeftLeft->left = rootRightLeftLeft->right = NULL;
struct TreeNode *rootRightLeft = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRightLeft->val = 3;
rootRightLeft->left = rootRightLeftLeft;
rootRightLeft->right = rootRightLeftRight;
struct TreeNode *rootRight = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRight->val = 2;
rootRight->left = rootRightLeft;
rootRight->right = NULL;
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = NULL;
root->right = rootRight;
int resultSize = 0;
int *result = postorderTraversal(root, &resultSize);
printArr(result, resultSize);
free(result);
free(rootRightLeftRight);
free(rootRightLeftLeft);
free(rootRightLeft);
free(rootRight);
free(root);
}