讨论/《深度优先搜索》 - 练习:路径总和/
《深度优先搜索》 - 练习:路径总和
共 5 个回复
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == NULL)
        {
            return false;
        }
        if(root->left==NULL && root->right==NULL)
        {
            return targetSum == root->val;
        }
        return hasPathSum(root->left,targetSum-root->val)||hasPathSum(root->right,targetSum-root->val);
    }
};
2
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        } else if (root.left == null && root.right == null) {
            return root.val == targetSum;
        } else if (root.left == null && root.right != null) {
            return hasPathSum(root.right, targetSum - root.val);
        } else if (root.left != null && root.right == null) {
            return hasPathSum(root.left, targetSum - root.val);
        } else {
            return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
        }
    }
}
class Solution:
    def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
        if not root:
            return False
        if not root.left and not root.right:
            return root.val == targetSum
        return self.hasPathSum(root.left,targetSum-root.val) or self.hasPathSum(root.right,targetSum-root.val)
        
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) return false;
        if(root.left == null && root.right == null) return root.val == targetSum;
        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
    }
}
class Solution:
    def hasPathSum(self, root: TreeNode, T: int) -> bool:
        if not root : return False
        def check(root,T):
            T -= root.val
            if not root.left and not root.right : return not T
            if not root.left : return check(root.right,T)
            if not root.right : return check(root.left,T)
            return check(root.left,T) | check(root.right,T) 
        return check(root,T)