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.

Note: A leaf is a node with no children.

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.

 

 

这是一个递归的模板的在应用:

思路如下:

1. 当顶点是null的时候 没用sum的值 所以返回一个false 这是第一个限制条件

2.我们的设计思路是每次访问到一个节点我们都会用sum的值减去这个节点的值 我们可以看出这个路径总和其实是一个背包的问题。

3. 如果叶子节点的值不等于最后剩下的sum的值我们就认为此路不通 需要回溯到上一个节点。

4. 在这里我们只需要找到一条路径就行 所以当有true的情况的时候 则立即返回true

bool hasPathSum(struct TreeNode* root, int sum){
     if(root == NULL) return false;
   //  if(abs(root->val) > abs(sum)) return false;
     
    if(root->left == NULL && root->right == NULL && root->val == sum)
        return true;
    else{
         bool a =  hasPathSum(root->left,  sum - root->val);
         bool b =  hasPathSum(root->right, sum - root->val);
        return a | b;
    }
    return false;
}

我们来看代码 前面两个if语句是给递归做限定条件 一个if是当没用顶点的时候则没有路径所以返回的是false

第二个限定的条件是当到了叶子节点之后如果剩下的sum的值和其相等,则确定为唯一的成功的路径。

然后我们在else语句里面不断地访问子节点 就可以得到最后的路径

这种思路(模板)是动态规划解决背包的问题。

不是最快的解法 最快的解法应该是迭代的解法。

posted on 2020-04-22 07:21  闲云潭影  阅读(189)  评论(0编辑  收藏  举报