[Leetcode] Path Sum
Path Sum 题解
题目来源:https://leetcode.com/problems/path-sum/description/
Description
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Example
For example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
Solution
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root)
return false;
if (root -> val == sum &&
root -> left == NULL && root -> right == NULL)
return true;
return hasPathSum(root -> left, sum - (root -> val)) ||
hasPathSum(root -> right, sum - (root -> val));
}
};
解题描述
这道题题意是对给出的数字sum
,检索二叉树上根到叶子节点的路径,求路径上节点数据之和能否等于sum
。上面给出的是递归实现DFS的解法,下面给出的是BFS的解法:
class Solution {
private:
struct Task {
TreeNode *node;
int sum;
Task(TreeNode* n, int s) : node(n), sum(s) {}
};
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root)
return false;
queue<Task> q;
q.push(Task(root, sum));
while (!q.empty()) {
Task task = q.front();
q.pop();
TreeNode *node = task.node;
if (node -> left == NULL && node -> right == NULL &&
node -> val == task.sum)
return true;
if (node -> left) {
q.push(Task(node -> left, task.sum - (node -> val)));
}
if (node -> right) {
q.push(Task(node -> right, task.sum - (node -> val)));
}
}
return false;
}
};