[leetcode] #112 Path Sum (easy)

原题链接

题意:

给定一个值,求出从树顶到某个叶(没有子节点)有没有一条路径等于该值。

思路:

DFS

Runtime: 4 ms, faster than 100.00% of C++

class Solution
{
public:
  bool hasPathSum(TreeNode *root, int sum)
  {
    if (root == NULL)
      return false;
    if (root->val == sum && root->left==NULL && root->right==NULL)
      return true;

    return (root->left != NULL && hasPathSum(root->left, sum - root->val)) || (root->right != NULL && hasPathSum(root->right, sum - root->val));
  }
};

 

posted @ 2018-11-08 15:33  Ruohua3kou  阅读(163)  评论(0编辑  收藏  举报