112. 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.

 

 

 

 

class Solution {
public:
    
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr)  return false;

        if (root->left == nullptr && root->right == nullptr && targetSum == root->val) return true;
        
        return hasPathSum(root->left,targetSum-root->val) || hasPathSum(root->right,targetSum-root->val);
    }
};

 

 

 1 class Solution {
 2 public:
 3     bool res = false;
 4     void backtrack(TreeNode* root, int cursum, int targetSum) {
 5         if (root == nullptr) return;
 6         if(root->left == nullptr && root->right == nullptr) {
 7             // 需要加上叶子节点
 8             if (cursum + root->val == targetSum) {
 9                 res = true;
10                 return;
11             }
12         }
13         // 剪枝
14         if(!res) backtrack(root->left,cursum+root->val,targetSum);
15         if(!res) backtrack(root->right,cursum+root->val,targetSum);
16     }
17     
18     bool hasPathSum(TreeNode* root, int targetSum) {
19         if (root == nullptr) return res;
20         backtrack(root,0,targetSum);
21         return res;
22     }
23 };

 

 

posted @ 2017-11-01 21:40  乐乐章  阅读(164)  评论(0编辑  收藏  举报