@@ -12,50 +12,43 @@ struct node_backlog {
1212 struct TreeNode * right ;
1313};
1414
15- static int counting (struct TreeNode * node )
16- {
17- if (node == NULL ) {
18- return 0 ;
19- }
20- return 1 + counting (node -> left ) + counting (node -> right );
21- }
22-
2315/**
2416 ** Return an array of size *returnSize.
2517 ** Note: The returned array must be malloced, assume caller calls free().
2618 **/
2719static int * postorderTraversal (struct TreeNode * root , int * returnSize )
2820{
29- if (root == NULL ) {
30- return NULL ;
31- }
32-
33- * returnSize = counting (root );
34-
3521 int count = 0 ;
36- int * results = malloc (* returnSize * sizeof (int ));
37- struct node_backlog * stack = malloc (* returnSize * sizeof (* stack ));
22+ int * results = malloc (100 * sizeof (int ));
23+ struct node_backlog * stack = malloc (100 * sizeof (* stack ));
3824 struct node_backlog * top = stack ;
39- struct TreeNode * node = root ;
4025
41- while (node != NULL || top != stack ) {
42- if (node == NULL ) {
26+ /* root != NULL condition is just for the first iteration and
27+ * never push NULL into the stack
28+ */
29+ while (root != NULL || top != stack ) {
30+ if (root != NULL ) {
31+ /* push both parent and its right child */
32+ top -> parent = root ;
33+ top -> right = root -> right ;
34+ top ++ ;
35+ root = root -> left ;
36+ } else {
4337 if ((top - 1 )-> right != NULL ) {
44- node = (top - 1 )-> right ;
38+ /* switch to right child but not pop up the parent */
39+ root = (top - 1 )-> right ;
40+ /* avoid infinite loop */
4541 (top - 1 )-> right = NULL ;
4642 } else {
47- node = (-- top )-> parent ;
48- results [count ++ ] = node -> val ;
49- node = NULL ;
50- continue ;
43+ root = (-- top )-> parent ;
44+ results [count ++ ] = root -> val ;
45+ /* we need to backtrace */
46+ root = NULL ;
5147 }
5248 }
53- top -> parent = node ;
54- top -> right = node -> right ;
55- top ++ ;
56- node = node -> left ;
5749 }
5850
51+ * returnSize = count ;
5952 return results ;
6053}
6154
0 commit comments