[leetCode]257. 二叉树的所有路径

题目

链接:https://leetcode-cn.com/problems/binary-tree-paths

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

递归

class Solution {
    List<String> ans = new ArrayList<>();

    public List<String> binaryTreePaths(TreeNode root) {
        if (root == null) return ans;
        paths(root, "");
        return ans;
    }

    private void paths(TreeNode root, String path) {
        path += root.val;
        if (root.left == null && root.right == null) {
            ans.add(path);
        }

        if (root.left != null)
            paths(root.left, path+"->");// 隐藏着回溯
        if (root.right != null)
            paths(root.right, path+"->");// 隐藏着回溯
    }
}
posted @ 2020-11-03 16:12  消灭猕猴桃  阅读(48)  评论(0编辑  收藏  举报