标签:
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 };
标签:
原文地址:http://www.cnblogs.com/zhuguanyu33/p/4433879.html