DFS和BFS原理以及简单模板

【文章概要】

针对深度优先和广度优先搜索算法的基本原理介绍,以及相应的示例代码参考

【内容分析】

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

BFS算法简单模板

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值