## 题目描述

### 英文

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

``````Input:

1
/   \
2     3
\
5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3``````

### 中文

``````输入:

1
/   \
2     3
\
5

## 解法一

### 思路

• 第一次递归：输入`''`，输出`'1'`
• 第二次递归：输入`'1'`，左子结点输出`'1->2'`，右子结点输出`'1->3'`（右子结点为叶子结点，停止递归）。
• 第三次递归：输入`'1->2'`，左子结点的右子结点输出`'1->2->5'`（左子结点的右子结点为叶子结点，停止递归）。
• 输出：`'1->3'``'1->2->5'`

### Python

``````# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""

def paths(root, path, result):
if root.left is None and root.right is None:
result.append(path + str(root.val))
if root.left is not None:
paths(root.left, path + str(root.val) + '->', result)
if root.right is not None:
paths(root.right, path + str(root.val) + '->', result)

result = []
if root is not None:
paths(root, '', result)
return result``````

### Java

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
class Utils {
public void paths(TreeNode root, String path, List<String> result) {
if (root.left == null && root.right == null) {
result.add(path + root.val);
}
if (root.left != null) {
paths(root.left, path + root.val + "->", result);
}
if (root.right != null) {
paths(root.right, path + root.val + "->", result);
}
}
}
Utils utils = new Utils();
List<String> result = new ArrayList<>();
if (root != null) {
utils.paths(root, "", result);
}
return result;
}
}``````

### C++

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode *root) {
class Utils {
public:
void paths(TreeNode *root, string path, vector<string> &result) {
if (root->left == nullptr && root->right == nullptr) {
result.push_back(path + to_string(root->val));
}
if (root->left != nullptr) {
paths(root->left, path + to_string(root->val) + "->", result);
}
if (root->right != nullptr) {
paths(root->right, path + to_string(root->val) + "->", result);
}
}
};
vector<string> result;
if (root != nullptr) {
Utils utils;
utils.paths(root, "", result);
}
return result;
}
};``````