您的位置:首页 > 其它

LeetCode: Path Sum

2013-04-19 04:22 399 查看
少数次过

/**
* 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 hasPathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root) return false;
if (!root->left && !root->right) return sum == root->val;
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}
};


C#

/**
* Definition for a binary tree node.
* public class TreeNode {
*     public int val;
*     public TreeNode left;
*     public TreeNode right;
*     public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool HasPathSum(TreeNode root, int sum) {
if (root == null) return false;
if (root.left == null && root.right == null) return sum == root.val;
return HasPathSum(root.left, sum-root.val) || HasPathSum(root.right, sum-root.val);
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: