7

C++描述 LeetCode 112. 路径总和

 3 years ago
source link: https://blog.csdn.net/qiguanjiezl/article/details/111936651
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C++描述 LeetCode 112. 路径总和

  大家好,我叫亓官劼(qí guān jié ),在CSDN中记录学习的点滴历程,时光荏苒,未来可期,加油~博主目前仅在CSDN中写博客,唯一博客更新的地址为:亓官劼的博客 ,同时正在尝试在B站中做一些内容分享,B站主页为: 亓官劼的B站主页

本文原创为亓官劼,请大家支持原创,部分平台一直在恶意盗取博主的文章!!!
若需联系博主,可以联系本人微信:qiguanjie2015


给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2

我们可以从根结点递归的向下求解,当且仅当到叶子结点且当且val为当前剩余的sum时,为true,否则为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 == NULL)
            return false;
        if(root->right == NULL && root->left == NULL){
            if(sum == root->val)
                return true;
            else
                return false;
        }
        return hasPathSum(root->right,sum - root->val) || hasPathSum(root->left,sum - root->val);
            
    }
};
亓官劼 Python 全栈 数据结构与算法
大家好,我是亓官劼(qí guān jié),在博客中分享数据结构与算法、Python全栈开发、Java后端开发、前端、OJ题解及各类报错信息解决方案等经验。一起加油,用知识改变命运,未来可期。
若有事项需联系博主,可通过微信:qiguanjie2015 进行联系,有空会回复。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK