Path Sum | Leetcode 112 | C++

แชร์
ฝัง
  • เผยแพร่เมื่อ 9 พ.ย. 2024

ความคิดเห็น • 5

  • @naziausha6655
    @naziausha6655 ปีที่แล้ว +1

    Good explanation, thank you!

  • @pritishpattnaik4674
    @pritishpattnaik4674 2 ปีที่แล้ว +1

    Can u tell the error in my code , 99 testcases passed but 18 failed
    bool helper(TreeNode *root, int targetSum, int &sum){
    //base case
    if (root == NULL) return false;
    if (root->left == NULL and root->right == NULL and sum+root->val == targetSum){
    return true;
    }
    else if (root->left == NULL and root->right == NULL and sum+root->val != targetSum){
    return false;
    }

    sum += root->val;
    bool left = helper(root->left, targetSum, sum);
    bool right = helper(root->right, targetSum, sum);
    if (left or right) return true;
    return false;

    }

    bool hasPathSum(TreeNode* root, int targetSum) {
    int sum = 0;
    return helper(root, targetSum, sum);
    }

    • @KnowledgeCenter
      @KnowledgeCenter  2 ปีที่แล้ว

      Pass the sum by value instead of reference. Then all the testcases should pass.
      Sum is always getting incremented between the calls if you pass it by reference. Just change
      bool helper(TreeNode *root, int targetSum, int &sum){
      to
      bool helper(TreeNode *root, int targetSum, int sum){

    • @pritishpattnaik4674
      @pritishpattnaik4674 2 ปีที่แล้ว

      @@KnowledgeCenter Thanks sir , it worked