【Leetcode112】Path Sum

Runtime: 12 ms, faster than 76.30% of C++ online submissions for Path Sum.

Memory Usage: 19.8 MB, less than 97.92% of C++ online submissions for 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)
            return root->val == sum;
        else if(root->left == NULL && root->right != NULL){
            return hasPathSum(root->right, sum-root->val);
        }
        else if(root->left != NULL && root->right == NULL)
            return hasPathSum(root->left, sum-root->val);
        else{
            return hasPathSum(root->right, sum-root->val) || hasPathSum(root->left, sum-root->val);
        }
    }
};

目前想到的也就只有深度优先搜索

发布了112 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_39458342/article/details/103588161