File tree Expand file tree Collapse file tree 2 files changed +78
-0
lines changed
145_binary_tree_postorder_traversal Expand file tree Collapse file tree 2 files changed +78
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O2 -o test bst_postorder.c
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments