C++ solution recursive , count digits for each paths


#1
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
void sumNumbersInner(TreeNode* A, vector<pair<int, int>> & paths)
{
	if (A == nullptr) return ;

    // init with leaf	
	if (A->left == A->right && A->left == nullptr) // leaf
	{
		paths.emplace_back(make_pair(A->val, 0));
		return;
	}

	vector<pair<int, int>>  pathsLeft;
	sumNumbersInner(A->left, pathsLeft);
	
	for (auto & path : pathsLeft)
	{
		path.second += 1;
		int to_add = A->val;
		for (int i = 0; i < path.second; ++i) //must increase digits point for value
			to_add = (to_add * 10) % 1003;

		path.first = (path.first + to_add)%1003;
		paths.emplace_back(path);
	}
// repeat for right branch
	vector<pair<int, int>>  pathsRight;
	sumNumbersInner(A->right, pathsRight);
	
	
	for (auto & path : pathsRight)
	{
		path.second += 1;
		int to_add = A->val;
		for (int i = 0; i < path.second; ++i)
			to_add = (to_add * 10) % 1003;
		path.first = (path.first + to_add)%1003;
		paths.emplace_back(path);
	}

}

int Solution::sumNumbers(TreeNode* A){
	int res = 0;

	if (A == nullptr) return res;
	
	// holds digits path and digit count
	vector<pair<int, int>> paths;
	
	sumNumbersInner(A, paths);
	
	// do final sum  up for all paths
	for (auto i : paths)
	{
		res = (res + i.first)%1003;
	}

	return res;
}