少数次过
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool hasPathSum(TreeNode *root, int sum) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 if (!root) return false; 16 if (!root->left && !root->right) return sum == root->val; 17 return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val); 18 } 19 };
C#
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public bool HasPathSum(TreeNode root, int sum) { 12 if (root == null) return false; 13 if (root.left == null && root.right == null) return sum == root.val; 14 return HasPathSum(root.left, sum-root.val) || HasPathSum(root.right, sum-root.val); 15 } 16 }