• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Path Sum

少数次过

 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#

 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 }
View Code

 

posted @ 2013-04-19 04:22  ying_vincent  阅读(146)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3