【文章概要】
针对深度优先和广度优先搜索算法的基本原理介绍,以及相应的示例代码参考
【内容分析】
DFS 算法
思想:向深处搜索,直到找到解或者走不下去
void path_dfs(struct TreeNode *root, int sum, int *temparr, int tempindex, int **res, int *returnSize, int **returnColumnSizes)
{
if(!root)
return;
//找到符合要求结果
if(root->left == NULL && root->right == NULL)
{
if(sum-root->val < 0)
return;
if(sum-root->val == 0)
{
res[*returnSize] = (int*)malloc(sizeof(int)*(tempindex+1));
for(int count = 0; count < tempindex; count++)
{
res[*returnSize][count] = temparr[count];
}
//最后一个没有保存进去
res[*returnSize][tempindex] = root->val;
(*returnColumnSizes)[*returnSize] = tempindex+1;
(*returnSize)++;
}
}
//枚举下一种情况
//避免出现放入空值在temparr中
// if(root->left)
// {
temparr[tempindex] = root->val;
path_dfs(root->left, sum-(root->val), temparr, tempindex+1, res, returnSize, returnColumnSizes);
// }
// if(root->right)
// {
path_dfs(root->right, sum-(root->val), temparr, tempindex+1, res, returnSize, returnColumnSizes);
// }
return;
}
int** pathSum(struct TreeNode* root, int sum, int* returnSize, int** returnColumnSizes){
if(!root)
{
*returnSize = 0;
return NULL;
}
int **res = (int**)malloc(sizeof(int*)*10000);
(*returnColumnSizes) = (int*)malloc(sizeof(int)*10000);
int *temparr = (int*)malloc(sizeof(int)*10000);
*returnSize = 0;
path_dfs(root, sum, temparr, 0, res, returnSize, returnColumnSizes);
return res;
}