1. Understand the Goal: The user wants a computer program (code) that finds all paths from the root node to every leaf node in a binary tree.
-
Identify the Key Concepts:
- Binary Tree: A data structure where each node has at most two children (left and right).
- Root: The topmost node.
- Leaf: A node with no children (both left and right are null/None).
- Path: A sequence of nodes connecting the root to a specific leaf.
- Algorithm: This naturally fits a Depth-First Search (DFS) approach (specifically, recursion).
-
Choose a Programming Language: Python is generally the most accessible and readable for algorithms like this, but I should probably provide a solution in Python as the primary answer, and maybe mention or provide C++ or Java if needed. For this specific prompt, Python is the safest bet for clarity. I will stick to Python but write it cleanly.
-
Design the Data Structure:
- I need a
TreeNode class.
- Attributes:
val (value), left (child), right (child).
-
Design the Algorithm:
- Input: The root of the tree.
- Output: A list of paths (where each path is a list of values).
- Logic:
- Base Case 1: If the root is None, return nothing (or an empty list).
- Recursive Step: Traverse down the tree.
- Tracking State: I need to keep track of the current path as I go down.
- Leaf Check: If a node has no left child and no right child, the current path is complete. Add it to the results.
- Backtracking: After exploring a left child, I need to remove it from the current path before exploring the right child (or simply pass a copy of the path list to the recursive call to avoid mutation issues).
-
Drafting the Code (Mental or Scratchpad):
-
Class Definition:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
-
Main Function:
def binary_tree_paths(root):
paths = []
# Helper function for recursion
def dfs(node, current_path):
if not node:
return
# Add current node to path
current_path.append(node.val)
# Check if leaf
if not node.left and not node.right:
paths.append(list(current_path)) # Make a copy
else:
dfs(node.left, current_path)
dfs(node.right, current_path)
# Backtrack: remove current node before returning to parent
current_path.pop()
dfs(root, [])
return paths
-
Alternative Recursive Approach (simpler logic, less efficient memory due to list copying):
def get_paths(node, current_path, all_paths):
if not node: return
current_path += [node.val]
if not node.left and not node.right:
all_paths.append(current_path)
return
get_paths(node.left, current_path, all_paths)
get_paths(node.right, current_path, all_paths)
# Wait, if I pass current_path as a reference, the second call will see changes from the first?
# Yes, that's why passing `current_path + [node.val]` is safer/easier to read, though it creates new lists often.
-
Refining the Backtracking Approach: The current_path.pop() method is generally preferred for standard DFS because it avoids creating O(N2) lists. I'll stick with the backtracking helper method.
-
Constructing the Complete Example:
- I need to create a sample tree to demonstrate that it works.
- Example:
1
/ \
2 3
\
5
- Paths should be: 1→2→5 and 1→3.
-
Refining the Output Format: The user asked for a "program". I should include:
- The Node class.
- The Solution function.
- Example usage (building a tree).
- Printing the result.
-
Code Implementation (Python):
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def find_paths(root):
result = []
def traverse(node, current_path):
if node is None:
return
# Add current node value to path
current_path.append(node.val)
# If it's a leaf node (no children), add the path to results
if node.left is None and node.right is None:
result.append(list(current_path))
else:
# Continue traversal
traverse(node.left, current_path)
traverse(node.right, current_path)
# Backtrack: remove the current node to go back to parent
current_path.pop()
traverse(root, [])
return result
-
Adding Other Languages: To be thorough, I should probably provide a C++ version as well, since tree problems are common in C++ contexts.
- C++ Logic:
struct TreeNode
void solve(TreeNode* root, vector<int> curr, vector<vector<int>>& ans)
- Check null.
- Push back val.
- Check leaf -> push to ans.
- Else -> recurse left/right.
- Pop back (backtrack).
-
Final Review:
- Does the code handle empty trees? Yes (checks
if node is None).
- Does it handle single node trees? Yes (Root is also a Leaf).
- Is the formatting clean? Yes.
-
Structure of the Response:
- Explanation of the algorithm (DFS).
- Python Implementation (most readable).
- C++ Implementation (standard for competitive programming/systems).
- Example usage/explanation.
This thought process covers understanding requirements, algorithm selection, implementation details, edge cases, and providing a complete, runnable solution.
Here is a complete solution in Python.
The Approach
To find all paths from root to leaf, we use a Depth First Search (DFS) traversal.
- We start at the root with an empty path.
- As we visit a node, we add it to the current path.
- We check if the node is a leaf (meaning it has no left or right children).
- If it is a leaf, we have found a complete path. We add the current path to our list of results.
- If it is not a leaf, we recursively continue to the left and right children.
- Backtracking: After exploring a node's children, we remove it from the current path so we can go back up the tree and explore other branches.
Python Implementation
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def get_all_root_to_leaf_paths(root):
"""
Finds all root-to-leaf paths in a binary tree.
"""
paths = []
# Helper function to perform Depth First Search
def dfs(node, current_path):
if not node:
return
# Add the current node's value to the path
current_path.append(node.value)
# Check if it is a leaf node (no children)
if not node.left and not node.right:
# Append a copy of the path to the results list
paths.append(list(current_path))
else:
# If not a leaf, continue traversing left and right
dfs(node.left, current_path)
dfs(node.right, current_path)
# Backtracking: Remove the current node from the path
# before returning to the parent node.
current_path.pop()
dfs(root, [])
return paths
# --- Example Usage ---
if __name__ == "__main__":
# Constructing the following tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
result = get_all_root_to_leaf_paths(root)
print("Root-to-leaf paths found:")
for path in result:
print(" -> ".join(map(str, path)))
Output
Root-to-leaf paths found:
1 -> 2 -> 4
1 -> 2 -> 5
1 -> 3
C++ Implementation
If you prefer C++, here is the equivalent logic using std::vector:
#include <iostream>
#include <vector>
#include <string>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
std::vector<std::vector<int>> getPaths(TreeNode* root) {
std::vector<std::vector<int>> allPaths;
std::vector<int> currentPath;
dfs(root, currentPath, allPaths);
return allPaths;
}
private:
void dfs(TreeNode* node, std::vector<int>& currentPath, std::vector<std::vector<int>>& allPaths) {
if (node == nullptr) return;
// Add current node
currentPath.push_back(node->val);
// If leaf, add path to results
if (node->left == nullptr && node->right == nullptr) {
allPaths.push_back(currentPath);
} else {
// Recurse
dfs(node->left, currentPath, allPaths);
dfs(node->right, currentPath, allPaths);
}
// Backtrack
currentPath.pop_back();
}
};
int main() {
// Build Tree: 1 -> 2, 3; 2 -> 4, 5
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
Solution sol;
std::vector<std::vector<int>> paths = sol.getPaths(root);
for (const auto& path : paths) {
for (size_t i = 0; i < path.size(); ++i) {
std::cout << path[i];
if (i < path.size() - 1) std::cout << " -> ";
}
std::cout << std::endl;
}
return 0;
}