C語言重構【145】二叉樹的後序遍歷

所有題目源代碼:Git地址

題目

給定一個二叉樹,返回它的 後序 遍歷。

示例:

輸入: [1,null,2,3]  
   1
    \
     2
    /
   3 

輸出: [3,2,1]
進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?

方案:遞歸

  • 後續的迭代有些不同
  • 參看Java版的迭代實現
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
void getTreeSize(struct TreeNode *root, int *returnSize)
{
    if (root == NULL)
    {
        (*returnSize) = 0;
        return;
    }
    if (root->left != NULL)
    {
        (*returnSize)++;
        getTreeSize(root->left, returnSize);
    }
    if (root->right != NULL)
    {
        (*returnSize)++;
        getTreeSize(root->right, returnSize);
    }
    return returnSize;
}

int getVal(struct TreeNode *root, int *res, int index)
{
    if (root->left != NULL)
        index = getVal(root->left, res, index);
    if (root->right != NULL)
        index = getVal(root->right, res, index);
    res[index++] = root->val;
    return index;
}

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

    getVal(root, res, 0);

    return res;
}
複雜度計算
  • 時間複雜度:O(n)
  • 空間複雜度:O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章