欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 112 Path Sum

程序员文章站 2024-01-05 11:23:40
...

LeetCode 112

Path Sum

  • Problem Description:
    给出一棵二叉树,计算二叉树中从根节点到各个叶节点的节点和,如果其中存在等于题目给出的定值sum,则返回true,否则返回false.

    具体的题目信息:
    https://leetcode.com/problems/path-sum/description/

  • Example:
    LeetCode 112 Path Sum
  • Solution:
/**
 * 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->left == NULL && root->right == NULL && sum-root->val == 0) return true;
        return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right, sum-root->val);
    }
};
相关标签: tree recursion

上一篇:

下一篇: