二叉树的所有路径(力扣257题)

题目:

给定一个二叉树,返回所有从根节点到叶子节点的路径。说明: 叶子节点是指没有子节点的节点。

示例

输入:

   1
 /   
2     3
 
  5

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

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

分析:求出所有的路径,本质还是递归回溯,遍历所有可能的从根节点到叶子节点的路径,由于是二叉树的缘故,所以每次向下搜索时,可选的走向就只有两个,左孩子和右孩子,因为是求所有的路径的,所以左右孩子,只要存在,那就继续朝着存在的方向走,不存在就不走,如果同时不存在那么此时当前这个节点就是叶子节点,此条路径搜索完毕,那么就递归返回。

代码:

    private List<String> reslist;

    public List<String> binaryTreePaths(TreeNode root) {

        if (root == null){
            return new ArrayList<>();
        }

        String path = null;
        reslist = new ArrayList<>();
        findPathByDFS(root,path,reslist);

        return reslist;
    }

    private void findPathByDFS(TreeNode root,String path,List<String> reslist){

        if (root == null){
            return;
        }

        if (path != null){
            path = path +"->"+ root.val;
        }else {
            path = ""+root.val;
        }

        if (root.right==null && root.left==null){
            reslist.add(path);
            return;
        }

        if (root.left!=null){
            findPathByDFS(root.left,path,reslist);
        }

        if (root.right!=null){
            findPathByDFS(root.right,path,reslist);
        }
    }
原文地址:https://www.cnblogs.com/yxym2016/p/13252033.html