leetcode刷题之旅——112. Path Sum


        这道题目是easy题目当中通过率为32%的题目,是DFS算法的一道比较典型的题目。

题目大意:

        给定一个二叉树和一个sum值,如果在该二叉树中可以找到一个从根节点到叶节点的路径,通过节点值的和等于sum值,就返回true。

例子:

        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恰好与叶子节点的值相同,就说明存在这样一条路径,否则就不存在。

代码:

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



你可能感兴趣的:(c++,leetcode)