Practice › Trees
Root to Leaf Path Sum
Easy · Trees · Asked at Amazon, Microsoft, Meta, TCS, Infosys
Print YES if the tree has a root-to-leaf path whose node values add up to target, otherwise NO.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node. Third line: target.
Output
YES or NO.
Constraints
- 1 ≤ number of nodes ≤ 10^5
- 1 ≤ values ≤ 1000
- 1 ≤ target ≤ 10^9
Go down the tree subtracting each value from the target; at a leaf, check whether exactly zero remains.
Example 1
Input
13 5 4 8 11 -1 13 4 7 2 -1 -1 -1 1 22
Output
YES
Example 2
Input
3 1 2 3 5
Output
NO
Hints
- Carry the running sum from the root down.
- Only leaves end a root-to-leaf path — check the sum there.
Approach
DFS with an explicit stack of (node, sum of the path down to and including this node). When a leaf's sum equals the target, print YES. If the stack empties first, print NO. An explicit stack avoids recursion-depth limits on very tall trees.
Complexity: O(n) time · O(h) to 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 target;
cin >> target;
vector<pair<Node *, long long>> st = {{root, root->val}};
while (!st.empty()) {
auto _b = st.back();
auto n = _b.first;
auto sum = _b.second;
st.pop_back();
if (!n->left && !n->right && sum == target) {
cout << "YES\n";
return 0;
}
if (n->left) st.push_back({n->left, sum + n->left->val});
if (n->right) st.push_back({n->right, sum + n->right->val});
}
cout << "NO\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()))
k = data[0]
root = build(data[1 : 1 + k])
target = data[1 + k]
stack = [(root, root.val)]
found = False
while stack:
node, s = stack.pop()
if not node.left and not node.right and s == target:
found = True
break
if node.left:
stack.append((node.left, s + node.left.val))
if node.right:
stack.append((node.right, s + node.right.val))
print("YES" if found else "NO")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 target = next();
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 sum = (long) t[1];
if (n.left == null && n.right == null && sum == target) {
System.out.println("YES");
return;
}
if (n.left != null) st.push(new Object[] {n.left, sum + n.left.val});
if (n.right != null) st.push(new Object[] {n.right, sum + n.right.val});
}
System.out.println("NO");
}
}