题干:
代码;
class Solution {
public:bool traversal(TreeNode* node, int count){if(node == NULL)return false;if(!node -> left && !node -> right && count == 0)return true;if(!node -> left && !node -> right && count != 0)return false;if(node -> left){count -= node -> left -> val;if(traversal(node -> left, count))return true;count += node -> left -> val;}if(node -> right){count -= node -> right -> val;if(traversal(node -> right, count))return true;count += node -> right -> val;}return false;}bool hasPathSum(TreeNode* root, int targetSum) {if(root == NULL)return false;return traversal(root, targetSum - root -> val);}
};
注意count是从父节点开始减的,因为需要不断递归下去所以必须显示出方向,也即node -> left -> val。
另外必须判断root == NULL 情况,不管是在递归函数中还是在主函数中。
类似题:
代码:
class Solution {
public:void traversal(TreeNode* node, int count, vector<int>& path, vector<vector<int>>& res){// 添加当前节点的值到路径path.push_back(node->val);// 如果是叶子节点且路径和符合要求,则加入结果集if (!node->left && !node->right && count == node->val) {res.push_back(path);}// 继续向左子树递归if (node->left) {traversal(node->left, count - node->val, path, res);}// 继续向右子树递归if (node->right) {traversal(node->right, count - node->val, path, res);}// 回溯,移除当前节点的值path.pop_back();}vector<vector<int>> pathSum(TreeNode* root, int targetSum) {vector<int> path;vector<vector<int>> res;if (root == NULL) return res;traversal(root, targetSum, path, res);return res;}
};