Path and path-sum
Title description
Given a binary tree and a value sum, judge whether there is a path from the root node to the leaf node that the sum of the node values is equal to sum,
for example:
Given the following binary tree, sum=22,
return true, because there is a path 5-> The sum of the node values of 4->11->2 is 22
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 andsum = 22,
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
Problem-solving ideas
1. Recursive solution
- If root is NULL, return false
- If the leaf node is reached, and the value of sum minus the current leaf node is 0, return true
- In other cases, continue to recursively solve the left and right subtrees
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL)
return false;
if(root -> left == NULL && root -> right == NULL && sum - root -> val == 0)
return true;
return hasPathSum(root -> left, sum - root -> val) || hasPathSum(root -> right, sum - root -> val);
}
};
2. Backtracking
- Path: no need to record
- Selection list: non-empty left and right subtrees
- End condition: If the root is empty, return directly, as if the root is a leaf node
sum - root -> val == 0
returns true
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
bool res = false;
/*由于要从根节点的子树开始判断,所以要先单独对根节点进行判断*/
if(root == NULL) return false;
backtrack(root, sum, res);
return res;
}
void backtrack(TreeNode* root, int& sum, bool& res) {
if(root == NULL)
return ;
//如果到达叶子节点,且满足条件
if(root -> left == NULL && root -> right == NULL && sum - root -> val == 0) {
res = true;
return ;
}
//两个选择,只要子树不空就做选择
if(root -> left != NULL) {
sum -= root -> val;
backtrack(root -> left, sum, res);
sum += root -> val;
}
if(root -> right != NULL) {
sum -= root -> val;
backtrack(root -> right, sum, res);
sum += root -> val;
}
}
};
- Since there is no need to record the path for this question, there is no need to go to the backtracking, only dfs is needed
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
bool res = false;
if(root == NULL) return false;
dfs(root, sum, res);
return res;
}
void dfs(TreeNode* root, int sum, bool& res) {
if(root == NULL)
return ;
//如果到达叶子节点,且满足条件
if(root -> left == NULL && root -> right == NULL && sum - root -> val == 0) {
res = true;
return ;
}
//两个选择,只要子树不空就做选择
if(root -> left != NULL) {
dfs(root -> left, sum - root -> val, res);
}
if(root -> right != NULL) {
dfs(root -> right, sum - root -> val, res);
}
}
};