[Geeks for Geeks] Root to leaf paths sum

Root to leaf paths sum

Given a binary tree of N nodes, where every node value is a number. Find the sum of all the numbers which are formed from root to leaf paths.

  • Time : O(n)
  • Space : O(d)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void helper(Node* node, long long path, long long& res) {
if(!node) return;
path = path * 10 + node->data;
if(!node->left and !node->right) {
res += path;
} else {
helper(node->left, path, res);
helper(node->right, path, res);
}
}
long long treePathsSum(Node *root)
{
long long res = 0;
helper(root, 0, res);
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/root-to-leaf-paths-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.