Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
Return 3. The paths that sum to 8 are:
- 5 -> 3
- 5 -> 2 -> 1
- -3 -> 11
解析
求二叉树的路径等于一个给定的值,主要是路径的起点不一定是根节点,可以是所有的节点,但是必须是从父节点到子节点的路径。
解法1:自己原有的解法
构建一个pathsumofnode的函数以及一个findpath的函数,pathsumofnode用于计算从当前节点出发的路径是否等于sum,并计算路径条数。findpath用于递归遍历二叉树以获取路径条数。求解得到的pathsum就为当前节点的pathsumofnode以及pathsum(root->left)和pathsum(root-right)。
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if(!root)
return 0;
return pathSumofNode(root,sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
int pathSumofNode(TreeNode* root, int sum){
int count = 0;
findpath(root, sum, count);
return count;
}
void findpath(TreeNode* root, int sum, int& count){
if(!root) return;
sum -= root->val;
if(sum==0) count++;
findpath(root->left, sum, count);
findpath(root->right, sum, count);
}
};
解法2
先序遍历二叉树,每一个节点记录一条根节点到当前节点的路径,用一个变量cursum记录当前路径和。如果cursum等于sum,则count++,否则查看有没有满足sum的子路径,每次去掉一个点,看路径和是否等于sum,注意最后必须留一个节点,不能全去掉了,因为如果全去掉了,路径之和为0,而如果假如给定值刚好为0的话就会有问题。
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
int count = 0;
vector<TreeNode*> out;
findpath(root, sum, 0, out, count);
return count;
}
void findpath(TreeNode* root, int sum, int cursum, vector<TreeNode*> out, int& count){
if(!root) return;
cursum += root->val;
out.push_back(root);
if(cursum==sum) count++;
int t = cursum;
for(int i=0;i<out.size()-1;i++){
t -= out[i]->val;
if(t==sum) count++;
}
findpath(root->left, sum, cursum, out,count);
findpath(root->right, sum, cursum, out,count);
}
};
解法3
利用前序遍历,对于每个遍历到的节点进行处理,维护一个变量pre来记录之前路径之和,然后cur为pre加上当前节点值,如果cur等于sum,那么返回结果时要加1,然后对当前节点的左右子节点调用递归函数求解。
public:
int pathSum(TreeNode* root, int sum) {
if (!root) return 0;
return sumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
int sumUp(TreeNode* node, int pre, int& sum) {
if (!node) return 0;
int cur = pre + node->val;
return (cur == sum) + sumUp(node->left, cur, sum) + sumUp(node->right, cur, sum);
}
};