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


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

本文解析了LeetCode题目112路径总和的两种解法:使用BFS宽度优先搜索和分治法递归。通过具体代码实现展示了如何判断二叉树中是否存在一条从根节点到叶子节点的路径,该路径上节点值之和等于目标值。
1615

被折叠的 条评论
为什么被折叠?



