利用两个stack, 根节点先入栈S1, 弹出的通知把两个孩子按照左右的顺序加入S1,并把自己加入S2,依次循环直到S1为空,
然后依次S2出栈保存
[1,2,3]
s1:2 3
s2:1
s1:2
s2:1 3
s1:0
s2:1 3 2
S2出栈就是2 3 1 完成了后序访问
struct Stack{
struct ListNode * dummy;
};
void push(struct Stack * s, int val)
{
struct ListNode * node = calloc(1, sizeof(struct ListNode));
node->val = val;
node->next = s->dummy->next;
s->dummy->next = node;
}
int pop(struct Stack *s)
{
struct ListNode * p = s->dummy->next;
if(p){
s->dummy->next = p->next;
int ret = p->val;
free(p);
return ret;
}else{
printf("empty stack\n");
return -1;
}
}
struct Stack * init_stack()
{
struct Stack *s;
s = calloc(1, sizeof(struct Stack));
s->dummy = calloc(1, sizeof(struct ListNode));
return s;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
struct Stack * s1 = init_stack();
struct Stack * s2 = init_stack();
if(root == NULL)
return NULL;
push(s1,(int)root);
while(s1->dummy->next){
struct TreeNode *node = (struct TreeNode *)pop(s1);
if(node->left)
push(s1, (int)node->left);
if(node->right)
push(s1, (int)node->right);
push(s2, (int)node);
}
*returnSize = 0;
int *ret = calloc(*returnSize, sizeof(int));
//int *ret = calloc(10000, sizeof(int));
while(s2->dummy->next){
struct TreeNode * node= (struct TreeNode *)pop(s2);
ret = realloc(ret, (*returnSize+1)*sizeof(int));
ret[*returnSize] = node->val;
*returnSize +=1;
}
return ret;
}
网友评论