Path Sum

这篇博客探讨了如何解决在二叉树中寻找根到叶子节点路径,使得路径上所有节点值之和等于给定的目标和的问题。提供了两种不同的思路:一种是递归过程中保存路径,另一种是在遍历过程中收集符合条件的路径。

题目:

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      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

思路:

类似于二叉树的先序遍历算法。

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(!root)
            return false;
        if(root->left==NULL && root->right==NULL)  
        {
            if(root->val==sum)
                return true;
            else return false;
        }
        return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val);        
    }
};


题目II:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

 

思路1:


相对于第一题的 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:     vector<vector<int> > pathSum(TreeNode *root, int sum) {         // Start typing your C/C++ solution below         // DO NOT write int main() function         vector<vector<int> > result;         if(!root)             return result;         vector<int> myvector;         if(root->left==NULL && root->right==NULL && root->val==sum)         {             myvector.push_back(root->val);             result.push_back(myvector);               return result;         }         if(root->left!=NULL)         {             vector<vector<int> > tmp = pathSum(root->left,sum-root->val);             for(int i=0;i<tmp.size();i++)             {                 tmp[i].insert(tmp[i].begin(),root->val);                 result.push_back(tmp[i]);             }         }         if(root->right!=NULL)         {             vector<vector<int> > tmp = pathSum(root->right,sum-root->val);             for(int i=0;i<tmp.size();i++)             {                 tmp[i].insert(tmp[i].begin(),root->val);                 result.push_back(tmp[i]);             }         }           return result;         } }; 

 

上述中,我们是先序遍历,所以需要把当前节点插入到前面: tmp[i].insert(tmp[i].begin(),root->val); 否则顺序是相反的。

这里是逐步生成路径的,先生成底层的节点路径,将满足条件的部分路径(符合条件的部分路径节点)返回,作为上层路径的子路径,加入到尾部。这样一直到根节点。

思路2:

思路一是保存返回值,我们也可以一边遍历,一边保存值,将符合条件的遍历路径保存到result中。

我们每访问一个节点,都会保存该节点(不管他是否是符合条件路径中的节点),然后遍历到叶节点后,判断由根到该叶节点的路径是否符合sum要求,如果符合,则压入全局变量 result 中。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    vector<vector<int> > result;
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        result.clear();
        vector<int> myvector;
        findPathSum(root,sum,myvector);
        return result;
    }
    void findPathSum(TreeNode * root,int sum,vector<int> myvector)
    {
        if(!root)
            return;
        myvector.push_back(root->val);
        if(root->left==NULL && root->right==NULL && sum==root->val)
        {
            result.push_back(myvector);
        }
        if(root->left!=NULL)
            findPathSum(root->left,sum-root->val,myvector);
        if(root->right!=NULL)
            findPathSum(root->right,sum-root->val,myvector);

    }   
    
};


该代码更容易理解。

如果 将 findPathSum(TreeNode * root,int sum,vector<int> myvector) 里的 myvector 改为引用型参数 findPathSum(TreeNode * root,int sum,vector<int> & myvector)
 ,结果就不对了。

因为递归过程中产生的一些路径,我们需要用一些新的 myvector 来保存,每一个路径(不管是否符合sum要求)都需要保存在myvector 中。

所以如果用引用,则所以的临时路径都保存在myvector 中,会出现错误。

但传值的话,就会让 

findPathSum(root->right,sum-root->val,myvector);

findPathSum(root->left,sum-root->val,myvector);

进入循环后,都有自己的单独的 临时变量 myvector 。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值