The challenge
Return every complete root-to-leaf path in left-to-right order.
A leaf has no children. Let L be the total number of values copied into all returned paths.
Example
Balanced example: [8,4,2], [8,4,6], [8,12,10], [8,12,14]. A single node gives one one-value path.
Use the walkthrough below to inspect the input and each state change.
See Root-to-leaf paths, step by step
Follow the branches. Watch the state change.
View child pointers & node state
| Node | Value | Left | Right | State |
|---|---|---|---|---|
| A | 8 | B | C | — |
| B | 4 | D | E | — |
| C | 12 | F | G | — |
| D | 2 | null | null | — |
| E | 6 | null | null | — |
| F | 10 | null | null | — |
| G | 14 | null | null | — |
Inspect the input.
Labels identify node objects; numbers are their values. Left and right child pointers define the tree.
root = A:8View original input
A:8 [L:B, R:C] · B:4 [L:D, R:E] · C:12 [L:F, R:G] · D:2 [L:null, R:null] · E:6 [L:null, R:null] · F:10 [L:null, R:null] · G:14 [L:null, R:null]
Node IDs stay distinct even when values repeat. Pointer mutations update the diagram; removed nodes remain in the state table for reference.
Put it into code
Share one working path during recursion and copy it only at a leaf.
Nodes store value, left, and right. C++ uses C++17 or later.
from collections import deque
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def root_paths(root):
out, path = [], []
def visit(node):
if node is None:
return
path.append(node.value)
if node.left is None and node.right is None:
out.append(path.copy())
else:
visit(node.left)
visit(node.right)
path.pop()
visit(root)
return out
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
#include <map>
#include <optional>
#include <queue>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
struct Node {
long long value;
Node *left = nullptr, *right = nullptr;
explicit Node(long long v) : value(v) {}
};
vector<vector<long long>> root_paths(Node* root) {
vector<vector<long long>> out;
vector<long long> path;
function<void(Node*)> visit = [&](Node* node) {
if (!node) return;
path.push_back(node->value);
if (!node->left && !node->right) out.push_back(path);
else { visit(node->left); visit(node->right); }
path.pop_back();
};
visit(root);
return out;
}