#257
Easy Algorithms Binary tree paths
String Backtracking Tree Depth-First Search Binary Tree
68.2% acceptance
Feb 27, 2026
7210
346
Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
Solution
Rust
Time O(n)
Space O(n)
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn binary_tree_paths(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<String> {
let mut result = Vec::new();
if let Some(node) = root {
Self::tree_dfs(&node, String::new(), &mut result);
}
result
}
fn tree_dfs(node: &Rc<RefCell<TreeNode>>, path: String, result: &mut Vec<String>) {
let node = node.borrow();
let new_path = if path.is_empty() {
node.val.to_string()
} else {
format!("{}->{}",path, node.val)
};
if node.left.is_none() && node.right.is_none() {
result.push(new_path);
return;
}
if let Some(left) = &node.left {
Self::tree_dfs(left, new_path.clone(), result);
}
if let Some(right) = &node.right {
Self::tree_dfs(right, new_path, result);
}
}
}