题解 | #二叉树的前序遍历#递归与非递归

二叉树的前序遍历

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;
	}

全部评论

相关推荐

06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务