码迷,mamicode.com
首页 > 其他好文 > 详细

112 Path Sum 路径总和

时间:2018-04-05 01:32:54      阅读:376      评论:0      收藏:0      [点我收藏+]

标签:amp   gpo   div   body   ems   ==   desc   for   log   

给定一棵二叉树和一个总和,确定该树中是否存在根到叶的路径,这条路径的所有值相加等于给定的总和。
例如:
给定下面的二叉树和 总和 = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
返回 true, 因为存在总和为 22 的根到叶的路径 5->4->11->2。
详见:https://leetcode.com/problems/path-sum/description/

/**
 * 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)
        {
            return false;
        }
        if(root->left==nullptr&&root->right==nullptr&&root->val==sum)
        {
            return true;
        }
        return (hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val));
    }
};

 

112 Path Sum 路径总和

标签:amp   gpo   div   body   ems   ==   desc   for   log   

原文地址:https://www.cnblogs.com/xidian2014/p/8719543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!