leetcode-145. 二叉树的后序遍历-C语言

/*
 * 算法思想:
 * 使用两个栈,一个son stack一个root stack,其中son子节点,root用来存放父节点,
 * 迭代过程为:
 * 1. 每次从son stack中取出一个节点node, 压栈到root stack中去;
 * 2. 然后判断该节点node是否有左孩子,有的话压栈到son stack;
 * 3. 判断该节点node是否有右孩子,有的话,压栈到son stack;
 * 4. 当son stack中有元素的话,一直将上述1-3过程循环下去,循环结束后,root stack中的元素即为结果;
 * 5. 依次pop root stack中的元素,顺序即为后序遍历的结果。
 */

#define LEN 100
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
    struct TreeNode *node;
    struct TreeNode **root_stack;
    struct TreeNode **son_stack;
    int *arr;
    int root_index = 0;
    int son_index = 0;
    int arr_index = 0;
    
    if(!root) {
        *returnSize = 0;
        return NULL;
    }
    
    root_stack = (struct TreeNode **)malloc(LEN * sizeof(struct TreeNode *));
    son_stack = (struct TreeNode **)malloc(LEN * sizeof(struct TreeNode *));
    
    arr = (int *)malloc(LEN * sizeof(int));
    
    if(!root)
        return NULL;
    
    node  = root;
    son_stack[son_index++] = node;
    
    while(son_index){
        node = son_stack[--son_index];
        
        root_stack[root_index++] = node;
        
        if(node->left)
            son_stack[son_index++] = node->left;
        
        if(node->right)
            son_stack[son_index++] = node->right;
    }
    
    
    while(root_index){
        node = root_stack[--root_index];
        
        arr[arr_index++] = node->val;
    }
    
    free(son_stack);
    free(root_stack);
    
    *returnSize = arr_index;
    
    return arr;    
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值