LeetCode 437. 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.
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

  10
 /  \
5   -3
/ \    \
3   2   11
/ \   \
3  -2   1

Return 3. The paths that sum to 8 are:

  1. 5 -> 3
  2. 5 -> 2 -> 1
  3. -3 -> 11

分析:
1. 对整个树遍历,每个节点都向下寻找固定和的路径数量;
2. 使用递归运算计算二叉树路径和;
2. 计算孩子值之间,设置了临时的路径和temp,确保查找其他孩子时,之前路径的和不变(因为我将当前路径和sum、满足路径总数cnt都进行传参,不知道怎么在递归返回的时候同时传递修改的sum和cnt,所以就使用临时值进行了替代);
3. 在判断路径和是否与目标一致时,若一致直接返回会发现有一些测试集不能通过(我就是),将路径总和+1后,应该向下继续计算,万一后面的数据加和很不凑巧的等于0呢。。。。直到计算到叶子节点。

/**
 * 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:
    int pathSum(TreeNode* root, int sum) {
        if(root==NULL)
            return 0;
        int cnt=0;
        int target=sum;
        cnt=preOrder(root,cnt,0,target);
        return cnt;
    }
private:
    int preOrder(TreeNode* root,int cnt,int sum,int target){    //先序遍历
        if(root!=NULL){
            cnt=pathCnt(root,cnt,0,target);
            cnt=preOrder(root->left,cnt,0,target);
            cnt=preOrder(root->right,cnt,0,target);
        }
        return cnt;
    }
    int pathCnt(TreeNode* root,int cnt,int sum,int target){
        sum+=root->val;
        if(sum==target){    //判断路径和
            ++cnt;
        }
        int temp=sum;   //设置临时的路径和
        if(root->left){
            cnt=pathCnt(root->left,cnt,sum,target);
        }
        sum=temp;
        if(root->right){
             cnt=pathCnt(root->right,cnt,sum,target);
        }
        return cnt;
    }
};

你可能感兴趣的:(LeetCode)