給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
輸入:
1
/ \
2 3
\
5
輸出: ["1->2->5", "1->3"]
解釋: 所有根節點到葉子節點的路徑爲: 1->2->5, 1->3
void EveryPath(struct TreeNode *root,char **bin_trees,int *path,int depth,int *returnSize)
{
int i;
if (root ==NULL)
return ;
if (root->left ==NULL && root->right ==NULL){
path[depth]=root->val;
bin_trees[*returnSize] =(char *)calloc(1,sizeof(char *) *100);
for(i=0;i<depth ;i++)
{
sprintf(bin_trees[*returnSize],"%s%d->",bin_trees[*returnSize],path[i]);
}
sprintf(bin_trees[*returnSize],"%s%d",bin_trees[*returnSize],path[i]);
*returnSize+=1;
}else{
path[depth++]=root->val;
EveryPath(root->left,bin_trees,path,depth,returnSize);
EveryPath(root->right,bin_trees,path,depth,returnSize);
}
}
char ** binaryTreePaths(struct TreeNode* root, int* returnSize){
*returnSize =0;
int path[100]={0};
char **bin_trees =(char **)malloc(sizeof(char *) *100);
if (root==NULL)
return NULL;
EveryPath(root,bin_trees,path,0,returnSize);
return bin_trees;
}
這道題的問題在於輸入[]時,提交時報錯了
:執行出錯信息:Line 209: Char 3: runtime error: load of null pointer of type 'char *' (__Serializer__.c)
錯誤的原因
需要將*returnSize 設置爲0 在返回。