LeetCode257. 二叉树的所有路径

一看就会一写就废(╯﹏╰)

☆☆☆方法1:DFS前序遍历。路径是从根开始的, 于是想到前序遍历

☆☆☆方法2:BFS层序遍历。

☆☆☆☆方法3:递归。

代码1:

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        dfs(root, "", res);
        return res;
    }
    private void dfs(TreeNode root, String path, List<String> res) {
        if (root == null) return;
        //如果是叶子节点,说明找到了一条路径,把它加入到res中
        if (root.left == null && root.right == null) {
            res.add(path + root.val);
            return;
        }
        dfs(root.left, path + root.val + "->",res);
        dfs(root.right,path + root.val + "->" ,res);
    }
}

代码2:

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        /**
         * 方法2:BFS层序遍历
         *      维护两个队列,分别存储节点以及根到该节点的路径
         *      如果是叶子节点,则将对应的路径添加到结果中
         */
        List<String> paths = new ArrayList<>();
        if (root == null) return paths;
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        Queue<String> pathQueue = new LinkedList<>();
        nodeQueue.offer(root);
        pathQueue.offer(String.valueOf(root.val));
        while (!nodeQueue.isEmpty()) {
            TreeNode cur = nodeQueue.poll();
            String path = pathQueue.poll();
            // 叶子节点
            if (cur.left == null && cur.right == null) {
                paths.add(path);
            }else {
                if (cur.left != null) {
                    nodeQueue.offer(cur.left);
                    pathQueue.offer(new StringBuilder(path).append("->").append(cur.left.val).toString());
                }
                if (cur.right != null) {
                    nodeQueue.offer(cur.right);
                    pathQueue.offer(new StringBuilder(path).append("->").append(cur.right.val).toString());
                }
            }
        }
        return paths;
    }
}

代码3:

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        if (root.left == null && root.right == null) {
            res.add(String.valueOf(root.val));
            return res;
        }
        List<String> leftS = binaryTreePaths(root.left);
        for (String path : leftS) {
            res.add(root.val + "->" + path); // 组成更长的路径
        }
        List<String> rightS = binaryTreePaths(root.right);
        for (String path : rightS) {
            res.add(root.val + "->" + path);
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/HuangYJ/p/14180683.html