This is the link to the title
Let's look at the code of the problem
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
int BinaryTreeSize(struct TreeNode* root)
{
if (root == NULL)
return 0;
return BinaryTreeSize(root->left) + BinaryTreeSize(root->right) + 1;
}
void preorder(struct TreeNode* root,int* a,int*pi)
{
if (root == NULL)
return;
a[(*pi)++] = root->val;
preorder(root->left, a, pi);
preorder(root->right, a, pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize = BinaryTreeSize(root);
int* a = (int*)malloc(sizeof(int) * (*returnSize));
int pi = 0;
preorder(root, a, &pi);
return a;
}
There is a caveat: the output is an array, not ' returnSize'.