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

在这里插入图片描述
在这里插入图片描述

BFS解法

/**
 * 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);
    }
};

在这里插入图片描述

分治法-递归解法

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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/SL_World/article/details/114300393