LeetCode | Path Sum

题目:

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.

For 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.

思路:

利用递归的方法,当左右子节点都是NULL的时候能够判断当前节点是叶子节点。

代码:

/**
 * Definition for binary tree
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root == NULL)
        {
            return false;
        }
        return pathSum(root, 0, sum);
    }
    
    bool pathSum(TreeNode * p, int total, int sum)
    {
        if((p->left == NULL) && (p->right == NULL))
        {
            if(total + p->val  == sum)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else if(p->left == NULL)
        {
            return pathSum(p->right, p->val + total, sum);
        }
        else if(p->right == NULL)
        {
            return pathSum(p->left, p->val + total, sum);
        }
        else
        {
            return pathSum(p->left, p->val + total, sum) || pathSum(p->right, p->val + total, sum);
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11787805
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞