Practice › Trees
Sum of Root to Leaf Numbers
Medium · Trees · Asked at Amazon, Microsoft, Google, Meta
Every node holds one digit (0–9). Each root-to-leaf path spells a number — the path 1 → 2 → 3 spells 123. Print the sum of the numbers of all root-to-leaf paths.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node.
Output
The sum of all root-to-leaf numbers.
Constraints
- 1 ≤ number of nodes ≤ 10^4
- 0 ≤ values ≤ 9
- the tree height is at most 15
Pass the number built so far down the tree: child value = parent value × 10 + digit. Add it to the total at each leaf. The sum can exceed 2^31.
Example 1
Input
3 1 2 3
Output
25
Example 2
Input
5 4 9 0 5 1
Output
1026
Hints
- Going one level down appends a digit: number × 10 + digit.
- Add the number to the total only at leaves.
- With height up to 15 and many leaves, the total needs 64 bits.
Approach
DFS with a stack of (node, number spelled from the root to this node). For a child, the number becomes parent × 10 + child digit. At a leaf, add its number to the total. Each number has at most 15 digits and the sum of all of them stays well inside a signed 64-bit integer for these limits.
Complexity: O(n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// level order with -1 for a missing child
Node *build(const vector<long long> &a) {
if (a.empty() || a[0] == -1) return nullptr;
Node *root = new Node(a[0]);
queue<Node *> q;
q.push(root);
size_t i = 1;
while (!q.empty() && i < a.size()) {
Node *cur = q.front();
q.pop();
if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
i++;
if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
i++;
}
return root;
}
vector<long long> readTree() {
int k;
cin >> k;
vector<long long> a(k);
for (auto &x : a) cin >> x;
return a;
}
int main() {
Node *root = build(readTree());
long long total = 0;
vector<pair<Node *, long long>> st = {{root, root->val}};
while (!st.empty()) {
auto _b = st.back();
auto n = _b.first;
auto num = _b.second;
st.pop_back();
if (!n->left && !n->right) total += num;
if (n->left) st.push_back({n->left, num * 10 + n->left->val});
if (n->right) st.push_back({n->right, num * 10 + n->right->val});
}
cout << total << "\n";
return 0;
}Python solution
import sys
from collections import deque
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build(a):
"""Level order with -1 for a missing child."""
if not a or a[0] == -1:
return None
root = Node(a[0])
q = deque([root])
i = 1
while q and i < len(a):
cur = q.popleft()
if i < len(a) and a[i] != -1:
cur.left = Node(a[i])
q.append(cur.left)
i += 1
if i < len(a) and a[i] != -1:
cur.right = Node(a[i])
q.append(cur.right)
i += 1
return root
data = list(map(int, sys.stdin.read().split()))
root = build(data[1 : 1 + data[0]])
total = 0
stack = [(root, root.val)]
while stack:
node, num = stack.pop()
if not node.left and not node.right:
total += num
if node.left:
stack.append((node.left, num * 10 + node.left.val))
if node.right:
stack.append((node.right, num * 10 + node.right.val))
print(total)Java solution
import java.io.*;
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// level order with -1 for a missing child
static Node build(long[] a) {
if (a.length == 0 || a[0] == -1) return null;
Node root = new Node(a[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < a.length) {
Node cur = q.poll();
if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
i++;
if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
i++;
}
return root;
}
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static long next() throws IOException {
in.nextToken();
return (long) in.nval;
}
static long[] readTree() throws IOException {
int k = (int) next();
long[] a = new long[k];
for (int i = 0; i < k; i++) a[i] = next();
return a;
}
public static void main(String[] args) throws IOException {
Node root = build(readTree());
long total = 0;
ArrayDeque<Object[]> st = new ArrayDeque<>();
st.push(new Object[] {root, root.val});
while (!st.isEmpty()) {
Object[] t = st.pop();
Node n = (Node) t[0];
long num = (long) t[1];
if (n.left == null && n.right == null) total += num;
if (n.left != null) st.push(new Object[] {n.left, num * 10 + n.left.val});
if (n.right != null) st.push(new Object[] {n.right, num * 10 + n.right.val});
}
System.out.println(total);
}
}Solve Sum of Root to Leaf Numbers online · All practice problems