代码:
/**
* 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().
*/
typedef struct TreeNode TreeNode;
//计算二叉树的节点个数
int BinaryTreeSize(TreeNode* root)
{
if(root == NULL)
{
return 0;
}
return BinaryTreeSize(root->left)+BinaryTreeSize(root->right)+1;
}
//前序遍历
void preOrder(TreeNode* root,int* arr,int* n)
{
if(root == NULL)
{
return;
}
arr[(*n)++] = root->val;
preOrder(root->left,arr,n);
preOrder(root->right,arr,n);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
//计算二叉树的节点个数
* returnSize = BinaryTreeSize(root);
//申请空间
int* arr = (int*)malloc(sizeof(int)*(* returnSize));
//前序遍历
int n = 0;
preOrder(root,arr,&n);
return arr;
}