LeetCode Path Sum
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool hasPathSum(TreeNode *root, int sum) { return dfs(root, 0, sum); } bool dfs(TreeNode* root, int cur_sum, int target) { if (root == NULL) return false; cur_sum = cur_sum + root->val; if (cur_sum == target && root->left == NULL && root->right == NULL) return true; if (dfs(root->left, cur_sum, target)) return true; if (dfs(root->right, cur_sum, target)) return true; return false; } };
水一发