先序遍历,套模版就是了。

class Solution {
public:
    /**
     *
     * @param root TreeNode类
     * @param sum int整型
     * @return bool布尔型
     */
    bool hasPathSum(TreeNode* root, int sum) {
        // write code here
        if (!root) return false;
        return preOrder(root, sum, 0);
    }

    bool preOrder(TreeNode *root, int &sum, int current) {
        if (!root) return false;
        current += root->val;
        if (!root->left && !root->right && sum == current) return true;
        return preOrder(root->left, sum, current) || preOrder(root->right, sum, current);
    }
};