leetcode Path Sum
题目连接
https://leetcode.com/problems/path-sum/
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) { return dfs(root, 0, sum); } bool dfs(TreeNode *x, int cur, int sum) { if (!x) return false; if (!x->left && !x->right) { if (sum == cur + x->val) return true; } if (dfs(x->left, cur + x->val, sum)) return true; if (dfs(x->right, cur + x->val, sum)) return true; return false; } };
By: GadyPu 博客地址:http://www.cnblogs.com/GadyPu/ 转载请说明