runtime error: member access within null pointer of type

  binary-tree, c++, runtime-error, tree

LeetCode Problem : Problem Link

Error Message :
Line 16: Char 18: runtime error: member access within null pointer of type ‘TreeNode’ (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:25:18

Here is My Code

Error is showing in this line : 3rd line of code

if(root->left==NULL and root->right==NULL and isleft==true)

Can you explain why this error occurs?

int sum = 0;
void helper(TreeNode* root, bool isleft)
{
    if (root->left == NULL and root->right == NULL and isleft == true) {
        sum = sum + root->val;
        return;
    }
    helper(root->left, true);
    helper(root->right, false);
}
int sumOfLeftLeaves(TreeNode* root)
{
    if (root == NULL)
        return 0;
    if (root->left == NULL and root->right == NULL)
        return 0;
    if (root->left == NULL and root->right) {
        helper(root->right, false);
        return sum;
    }
    if (root->left and root->right == NULL) {
        helper(root->left, true);
        return sum;
    }
    helper(root->left, true);
    helper(root->right, false);
    return sum;
}

Source: Windows Questions C++

LEAVE A COMMENT