码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 112 Path Sum

时间:2015-04-17 08:21:12      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

使用DFS来搜索有没有路从root到叶子有路径和为所给参数。 

主要注意DFS的基本格式。 一般在参数中,有个随时变化的量,然后一进入DFS的子函数中,先判断返回的满足条件,然后在分别用 

return DFS(,,,) 的样子接着往下走。 所以这就是DFS的基本递归格式。

如下面的代码一和二.

 class Solution {
 public:
    bool hasPathSum(TreeNode *root, int sum) {   // This is very similar to the usual DFS
        if(root == NULL)
            return false; 
        if(root->left==NULL && root->right == NULL && root->val == sum)
            return true; 
        return hasPathSum(root->left,sum - root->val) || hasPathSum(root->right,sum - root->val);
    }
};
 1  class Solution {
 2  public:
 3     bool dfs(TreeNode *node, int sum, int curSum)
 4     {
 5         if (node == NULL)
 6             return false; 
 7         if (node->left== NULL && node->right == NULL)
 8             return curSum + node->val == sum; 
 9 
10         return dfs(node ->left, sum,curSum+node->val) || dfs(node->right, sum, curSum+node->val);
11     }
12     bool hasPathSum(TreeNode *root, int sum) {   // This is very similar to the usual DFS
13         if(root == NULL)
14             return false; 
15         if(root->left==NULL && root->right == NULL && root->val == sum)
16             return true; 
17         return hasPathSum(root->left,sum - root->val) || hasPathSum(root->right,sum - root->val);
18     }
19 };

 

Leetcode 112 Path Sum

标签:

原文地址:http://www.cnblogs.com/zhuguanyu33/p/4433879.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!