leetcode 112. Path 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;
        if(root->left == NULL && root->right == NULL && root->val == sum)
            return true;
        else
            return hasPathSum(root->right,sum-root->val) || hasPathSum(root->left,sum-root->val);
    }
};
原文地址:https://www.cnblogs.com/strongYaYa/p/6772556.html