前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T123-路径总和

【leetcode刷题】T123-路径总和

作者头像
木又AI帮
发布2019-07-24 17:26:07
3260
发布2019-07-24 17:26:07
举报
文章被收录于专栏:木又AI帮木又AI帮

木又连续日更第75天(75/100)


木又的第123篇leetcode解题报告

二叉树类型第13篇解题报告

leetcode第112题:路径总和

https://leetcode-cn.com/problems/path-sum


【题目】

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

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

代码语言:javascript
复制
示例: 
给定如下二叉树,以及目标和 sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

【思路】

本题和【T122-二叉树的最小深度】较为类似,对于一个节点,如果无孩子节点,则判断剩余的和是否为node->val;如果有孩子节点,则递归遍历孩子节点。

【代码】

python版本

代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root:
            return False
        if not root.left and not root.right:
            return root.val == sum
        if root.left and root.right:
            return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
        if root.left:
            return self.hasPathSum(root.left, sum-root.val)
        if root.right:
            return self.hasPathSum(root.right, sum-root.val)

C++版本

代码语言:javascript
复制
/**
 * 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)
            return false;
        if(!root->left && !root->right)
            return root->val == sum;
        if(root->left && root->right)
            return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
        if(root->left)
            return hasPathSum(root->left, sum-root->val);
        return hasPathSum(root->right, sum-root->val);
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档