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

LeetCode #112 - Path Sum

程序员文章站 2024-01-05 12:27:28
...

题目描述:

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

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.

利用递归遍历二叉树所有可能的路径,判断路径和是否等于目标值。

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

 

上一篇:

下一篇: