題目
給定一個二叉樹,返回它的 後序 遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [3,2,1]
進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?
方案:遞歸
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;
}
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;
}
複雜度計算