# Simple C++ solution with comments [AC]

• The idea is to traverse the tree in a preorder fashion. We will first get the value from the left child and then the right child. We will return the sum of the left and right child. The base case for the following would be the child node and when the root is NULL.

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:

int helper(TreeNode* root, int val)
{
//base case
if(root==NULL)
return 0;
//get the next value
int temp = root->val + val*10;
// Child node
if(root->left==NULL && root->right ==NULL)
return temp;

//get the value from the left and right nodes
int left = helper(root->left, temp);
int right = helper(root->right, temp);
//return the sum
return left+right;
}
public:
int sumNumbers(TreeNode* root) {
return helper(root, 0);
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.