1

The following code is in C++ I am encountering the error of value is not usable in a constant expression error


int sumNumbers(TreeNode* root) {

    stack<pair<TreeNode*, int>> st;
    st.push(make_pair(root, root->val));
    int sum = 0;

    while(!st.empty()){
        pair<TreeNode*, int> temp = st.top();
        st.pop();
        TreeNode* node = temp.first;
        int value = temp.second;

        if(node->left==NULL && node->right==NULL){
            sum += value;
        }

        if(node->left){
            st.push(pair< node->left, value*10 + node->left->val >);
        }

        if(node->right){
            st.push(pair< node->right, value*10 + node->right->val >);
        }
    }

    return sum;
}

The error is in the line:

if(node->left){
            st.push(pair< node->left, value*10 + node->left->val >);
        }

The error is:

Line 29: Char 37: error: the value of 'node' is not usable in a constant expression st.push(pair< node->left, value*10 + node->left->val >);


I am not able to figure out why this error is encountered here?

2
  • Use make_pair() Commented Feb 2, 2019 at 0:21
  • Readability suggestion : if(auto nl = node->left) { st.push(make_pair< nl, value*10 + nl->val >); . An if statement may define a local variable for the value being compared. Commented Feb 2, 2019 at 0:42

1 Answer 1

6

You want to use make_pair instead to create an object, setting the template types automatically:

st.push(make_pair(node->left, value*10 + node->left->val));

And same for the right side.

Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, just use list initialization: st.push({node->left, value*10 + node->left->val})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.