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

    Note: A leaf is a node with no children.

    Example:

    1. Input:
    2. 1
    3. / \
    4. 2 3
    5. \
    6. 5
    7. Output: ["1->2->5", "1->3"]
    8. Explanation: All root-to-leaf paths are: 1->2->5, 1->3

    题意

    打印一棵树从根结点到叶结点的所有路径。

    思路

    简单的DFS处理即可。


    代码实现

    1. class Solution {
    2. public List<String> binaryTreePaths(TreeNode root) {
    3. List<String> ans = new ArrayList<>();
    4. if (root != null) {
    5. dfs(root, ans, "");
    6. }
    7. return ans;
    8. }
    9. private void dfs(TreeNode x, List<String> ans, String s) {
    10. s += s.equals("") ? x.val : "->" + x.val;
    11. if (x.left != null) {
    12. dfs(x.left, ans, s);
    13. }
    14. if (x.right != null) {
    15. dfs(x.right, ans, s);
    16. }
    17. if (x.left == null && x.right == null) {
    18. ans.add(s);
    19. }
    20. }
    21. }