每日LeetCode - 145. 二叉树的后序遍历(C语言)


C语言

#define NULL ((void *)0)
/**
 * Definition for a binary tree node.*/
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* postorderTraversal(struct TreeNode* root, int* returnSize){
    int* res = (int*)malloc(sizeof(res)*501);
    *returnSize=0;
    postorder(root, res, returnSize);
    return res;
}

void postorder(struct TreeNode* root, int*res, int* resSize){
    if (!root)
        return;

    postorder(root->left, res, resSize);
    postorder(root->right, res, resSize);
    res[(*resSize)++]=root->val;
}