二叉树本身就具有递归的性质,所以按照根->左子树->右子树的顺序遍历整个树。
/** * 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(). */ int TreeSize(struct TreeNode* root) { return root==NULL?0:TreeSize(root->left)+TreeSize(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=TreeSize(root); int* a=(int*)malloc(*returnSize * sizeof(int)); int i = 0; preorder(root, a, &i); return a; }