首页 > 代码库 > Leetcode#112 Path Sum

Leetcode#112 Path Sum

原题地址

 

注意空树即使sum=0也不算

 

代码:

 1 bool solve(TreeNode *root, int sum) { 2   if (!root->left && !root->right) 3     return sum == root->val; 4  5   return (root->left && solve(root->left, sum - root->val)) || (root->right && solve(root->right, sum - root->val)); 6 } 7  8 bool hasPathSum(TreeNode *root, int sum) { 9   if (!root)10     return false;11 12   return solve(root, sum);13 }

 

Leetcode#112 Path Sum