`
cozilla
  • 浏览: 91865 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[Leetcode] Path Sum

 
阅读更多

Path Sum

 
AC Rate: 872/2770
My Submissions

 

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) {
        if (root == NULL) 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);
    }
    
    
};

 

 

Path Sum II

 
AC Rate: 691/2584
My Submissions

 

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 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) {
        vector<vector<int> > res;
        if (root == NULL) return res;
        vector<int> v;
        gen(res, v, root, 0, sum);
        return res;
    }
    
    void gen(vector<vector<int> >& res, vector<int>& v, TreeNode* cur, int s, int sum) {
        v.push_back(cur->val);
        if (cur->left == NULL && cur->right == NULL) {
            if (s+cur->val == sum) res.push_back(v);
        }
        else {
            if (cur->left != NULL) gen(res, v, cur->left, s + cur->val, sum);
            if (cur->right!= NULL) gen(res, v, cur->right,s + cur->val, sum);
        }
        v.pop_back();
    }
};

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics