Skip to content

Commit 6eabacf

Browse files
Binary tree postorder traversal
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 634d295 commit 6eabacf

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test bst_postorder.c
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct TreeNode {
5+
int val;
6+
struct TreeNode *left;
7+
struct TreeNode *right;
8+
};
9+
10+
struct node_backlog {
11+
struct TreeNode *parent;
12+
struct TreeNode *right;
13+
};
14+
15+
/**
16+
** Return an array of size *returnSize.
17+
** Note: The returned array must be malloced, assume caller calls free().
18+
**/
19+
static int* postorderTraversal(struct TreeNode* root, int* returnSize)
20+
{
21+
if (root == NULL) {
22+
return NULL;
23+
}
24+
25+
int cap = 10000, count = 0;
26+
int *results = malloc(cap * sizeof(int));
27+
struct node_backlog *stack = malloc(cap / 16 * sizeof(*stack));
28+
struct node_backlog *top = stack;
29+
struct TreeNode *node = root;
30+
struct node_backlog nbl;
31+
32+
while (node != NULL || top != stack) {
33+
if (node == NULL) {
34+
nbl = *--top;
35+
if (nbl.right != NULL) {
36+
node = nbl.right;
37+
nbl.right = NULL;
38+
*top++ = nbl;
39+
} else {
40+
node = nbl.parent;
41+
results[count++] = node->val;
42+
node = NULL;
43+
continue;
44+
}
45+
}
46+
nbl.parent = node;
47+
nbl.right = node->right;
48+
*top++ = nbl;
49+
node = node->left;
50+
}
51+
52+
*returnSize = count;
53+
return results;
54+
}
55+
56+
int main(int argc, char **argv)
57+
{
58+
struct TreeNode root, node1, node2;
59+
root.val = 1;
60+
node1.val = 2;
61+
node2.val = 3;
62+
root.left = NULL;
63+
root.right = &node1;
64+
node1.left = &node2;
65+
node1.right = NULL;
66+
node2.left = NULL;
67+
node2.right = NULL;
68+
69+
int i, count = 0;
70+
int *results = postorderTraversal(&root, &count);
71+
for (i = 0; i < count; i++) {
72+
printf("%d ", results[i]);
73+
}
74+
printf("\n");
75+
return 0;
76+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy