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.

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.

思路:DFS递归

可以将此问题转化为左右子树是否存在何为sum-root->val的子情况。
这种问题bool函数一般分四步:

  1. 特殊情况为空为零的
  2. 返回值为true的终止情况
  3. 递归调用子函数的返回值判断情况
  4. 其余情况,返回值为false
    四步处理中应保证第二步第四步都有返回。
/**
 * Definition for a binary tree node.
 * 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==nullptr)//1.
            return false;
        int sub=sum-root->val;
        if(sub==0 && root->left==nullptr && root->right==nullptr)//2.
            return true;
        if(hasPathSum(root->left,sub)||hasPathSum(root->right,sub))//3.
            return true;
        return false;//4.
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 可以按照前序遍历的顺序遍历树,在遍历过程中,定义一个变量,这个变量等于sum减去已经被遍历过的所有节点的val。一...
    小碧小琳阅读 365评论 0 1
  • Description Given a binary tree and a sum, determine if t...
    Nancyberry阅读 129评论 0 0
  • Given a binary tree and a sum, determine if the tree has ...
    DrunkPian0阅读 172评论 0 0
  • Easy Given a binary tree and a sum, determine if the tree...
    greatseniorsde阅读 256评论 0 0
  • path sum 有好几题,是一个系列。 原题是: Given a binary tree and a sum, ...
    小双2510阅读 273评论 0 0

友情链接更多精彩内容