LeetCode 112 Path Sum (Path and) (BT, DP )(*)
Translation
Given a binary tree root and a sum, it determines whether the tree has a path from the root to the leaf so that the sum of all nodes along the road is equal to the given sum. For example, given the following binary tree and sum = 22, 5/\ 4 8 // \ 11 13 4/\ 7 2 1, return true, because there is a root leaf path (5-> 4-> 11-> 2), and its sum is 22.
Original
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.For example:Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Analysis
If it is a binary search tree, you can perform some subtraction based on its features to take a shortcut.
Use the most basic method to solve the problem:
bool hasPathSum(TreeNode* root, int sum) { if (!root) return false; if (!root->left && !root->right) return root->val == sum; return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);}
Then I thought, if the sum on a node has exceeded sum, it should be false. Then add a line:
if (root->val > sum) return false;
Oh no ...... It turns out that there are still negative numbers, and it is wrong. Forget it, don't count on it, continue to play ......
In fact, this is similar to the above, the difference is that the above judgment method is constantly using the given sum to lose the current value, and this is to continue to accumulate to see if the accumulation is just equal to sum, additional variables ......
bool dfs(TreeNode* root, int pasum, int sum) { if (!root) return false; if (!root->left && !root->right) return pasum + root->val == sum; return dfs(root->left, pasum + root->val, sum) || dfs(root->right, pasum+root->val, sum);}bool hasPathSum(TreeNode* root, int sum) { return dfs(root, 0, sum);}
Code
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public: bool dfs(TreeNode* root, int pasum, int sum) { if (!root) return false; if (!root->left && !root->right) return pasum + root->val == sum; return dfs(root->left, pasum + root->val, sum) || dfs(root->right, pasum + root->val, sum); } bool hasPathSum(TreeNode* root, int sum) { return dfs(root, 0, sum); }};