[LeetCode] Path Sum

来源:互联网 发布:网络三大奇书四大神书 编辑:程序博客网 时间:2024/05/14 08:09
/** * 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 ret;        void DFS(TreeNode *root, int remain) {        if (!root) return;                if (!root->left && !root->right && root->val == remain) {            ret = true;            return;        }                DFS(root->left, remain - root->val);        DFS(root->right, remain - root->val);    }        bool hasPathSum(TreeNode *root, int sum) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        ret = false;        DFS(root, sum);        return ret;    }};


Small Case: 8ms

Large Case: 96ms


Time: O(n)

Space: O(1)

原创粉丝点击