前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode|二叉树的属性|112. 路径总和

Leetcode|二叉树的属性|112. 路径总和

作者头像
SL_World
发布2021-09-18 15:24:17
2810
发布2021-09-18 15:24:17
举报
文章被收录于专栏:X

《Leetcode|二叉树的属性|112. 路径总和》

《Leetcode|二叉树的属性DFS回溯|113. 路径总和 II》

BFS解法

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool bfs(TreeNode* root, int targetSum) {
        if (root == nullptr) return false;
        queue<TreeNode*> q;
        queue<int> sum;
        q.push(root);
        sum.push(root->val);

        while (!q.empty()) {
            int sz = q.size();
            for (int i=0;i < sz;i++) {
                TreeNode* e_ptr = q.front(); q.pop();
                int s = sum.front(); sum.pop();
                
                if (e_ptr->left == nullptr && e_ptr->right == nullptr && s == targetSum) return true;
                if (e_ptr->left != nullptr) {
                    q.push(e_ptr->left);
                    sum.push(s + e_ptr->left->val);
                }
                if (e_ptr->right != nullptr) {
                    q.push(e_ptr->right);
                    sum.push(s + e_ptr->right->val);
                }
            }
        }
        return false; 
    }
    bool hasPathSum(TreeNode* root, int targetSum) {
        return bfs(root, targetSum);
    }
};

分治法-递归解法

代码语言:javascript
复制
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (root == nullptr) return false;
        if (root->left == nullptr && root->right == nullptr)
            return root->val == targetSum;
        return hasPathSum(root->left, targetSum - root->val) || 
        hasPathSum(root->right, targetSum - root->val);
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/03/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • BFS解法
  • 分治法-递归解法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档