257. Binary Tree Paths 发表于 2021-11-14 DFS123456789101112131415161718192021222324252627282930class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> list = new LinkedList<>(); Deque<Integer> path = new LinkedList<>(); dfs(list, path, root); return list; } private void dfs(List<String> list, Deque<Integer> path, TreeNode node) { if (node == null) { return; } path.add(node.val); if (node.left == null && node.right == null) { list.add(pathToString(path)); } dfs(list, path, node.left); dfs(list, path, node.right); path.removeLast(); } private String pathToString(Deque<Integer> path) { return path.stream().map(String::valueOf).collect(Collectors.joining("->")); }} BFS123456789101112131415161718192021222324252627282930class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> list = new LinkedList<>(); Queue<TreeNode> queue = new LinkedList<>(); Queue<String> pathQueue = new LinkedList<>(); queue.add(root); pathQueue.add(String.valueOf(root.val)); while (!queue.isEmpty()) { TreeNode node = queue.poll(); String path = pathQueue.poll(); if (node.left == null && node.right == null) { list.add(path); } if (node.left != null) { queue.add(node.left); pathQueue.add(path + "->" + node.left.val); } if (node.right != null) { queue.add(node.right); pathQueue.add(path + "->" + node.right.val); } } return list; }} Reference257. Binary Tree Paths