int* preorderTraversal( struct TreeNode*root, int* returnSize) {
}
解答代码:
int TreeSize(struct TreeNode*root){return root==NULL?0:TreeSize(root->left)+TreeSize(root->right)+1;}void Prevorder(struct TreeNode*root,int*a,int*pi){if(root==NULL)return;a[(*pi)++]=root->val;Prevorder(root->left,a,pi);Prevorder(root->right,a,pi);}
int* preorderTraversal( struct TreeNode*root, int* returnSize) {int n=TreeSize(root);int *a=(int*)malloc(sizeof(int)*n);*returnSize=n;int i=0;Prevorder(root,a,&i);return a;
}
ps:
题目里给的形参:int*returnSize 是个输出型变量 ,之所以给指针,是为了便于修改returnSize所指向的数值,这个数值就是数组中元素的个数