题解 | #二叉树的前序遍历#递归与非递归
二叉树的前序遍历
http://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
递归版本
```void preorder(struct TreeNode*root,int*ret,int*returnSize)
{
if(root!=NULL){
ret[(*returnSize)++]=root->val;
preorder(root->left, ret, returnSize);
preorder(root->right, ret, returnSize);
}
}
int* preorderTraversal(struct TreeNode* root, int* returnSize ) {
int*ret=(int*)malloc(sizeof(int)*100);
*returnSize=0;
preorder( root, ret,returnSize);
printf("retsize=%d",*returnSize);
return ret;
}
非递归版本
```int* preorderTraversal(struct TreeNode* root, int* returnSize ) {
if(root==NULL) return root;
int*ret=(int*)malloc(sizeof(int)*100);
*returnSize=0;
struct TreeNode * stack[100];
int top=-1;
stack[++top]=root;
while(top!=-1){
root=stack[top--];
ret[(*returnSize)++]=root->val;
if(root->right!=NULL){
stack[++top]=root->right;
}
if(root->left!=NULL){
stack[++top]=root->left;
}
}
return ret;
}