1. 题目

2. 思路
(1) DFS
- 利用深度优先搜索遍历二叉树,若遍历到叶子结点,则将当前路径加入结果集中即可。
3. 代码
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
}
}
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 {
private List<String> res;
public List<String> binaryTreePaths(TreeNode root) {
res = new ArrayList<>();
preorder(root, new StringBuilder());
return res;
}
private void preorder(TreeNode root, StringBuilder path) {
if (root == null) {
return;
}
path.append(root.val);
if (root.left == null && root.right == null) {
res.add(path.toString());
} else {
if (root.left != null) {
preorder(root.left, new StringBuilder(path).append("->"));
}
if (root.right != null) {
preorder(root.right, new StringBuilder(path).append("->"));
}
}
}
}