LeetCode: Path Sum I && II

Title:

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 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 hasPathSum(TreeNode* root, int sum) {
        if (!root)
            return false;
        if (!root->left && !root->right)
            return sum == root->val;
        //if (sum < 0)
            //return false;
        return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val);
    }
};

 

Title:

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]
]
/**
 * 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:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int> > results;
        vector<int> result;
        pathSum(root,sum,results,result);
        return results;
        
    }
    void pathSum(TreeNode* root,int sum, vector<vector<int> > &results, vector<int> &result){
        if (!root)
            return ;
        if (!root->left && !root->right){
            if (root->val == sum){
                result.push_back(root->val);
                results.push_back(result);
                result.pop_back();
            }
            return ;
        }
        result.push_back(root->val);
        pathSum(root->left,sum-root->val,results,result);
        pathSum(root->right,sum-root->val,results,result);
        result.pop_back();
    }
};

 

posted on 2015-05-14 20:57  月下之风  阅读(143)  评论(0编辑  收藏  举报

导航