257. Binary Tree Paths
2026/1/12小于 1 分钟约 269 字
257. Binary Tree Paths
难度: Easy
题目描述
Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
Example 1:

Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]
Example 2:
Input: root = [1] Output: ["1"]
Constraints:
- The number of nodes in the tree is in the range
[1, 100]. -100 <= Node.val <= 100
解题思路
代码实现
解决方案
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<String> res = new ArrayList<>();
binaryTreePaths2(root,"",res);
return res;
}
public void binaryTreePaths2(TreeNode root, String str, List<String> res) {
if(root==null){
return;
}
String newStr = str+root.val;
if (root.left == null && root.right == null) {
res.add(newStr);
return;
}
if (root.left != null) {
binaryTreePaths2(root.left, newStr + "->" , res);
}
if (root.right != null) {
binaryTreePaths2(root.right, newStr + "->", res);
}
}
}