[Leetcode][第257题][JAVA][二叉树的所有路径][BFS][DFS]

tech2025-06-09  19

【问题描述】[简单]

【解答思路】

1. DFS

时间复杂度:O(N^2) 空间复杂度:O(N^2)

class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> paths = new ArrayList<String>(); constructPaths(root, "", paths); return paths; } public void constructPaths(TreeNode root, String path, List<String> paths) { if (root != null) { StringBuffer pathSB = new StringBuffer(path); pathSB.append(Integer.toString(root.val)); if (root.left == null && root.right == null) { // 当前节点是叶子节点 paths.add(pathSB.toString()); // 把路径加入到答案中 } else { pathSB.append("->"); // 当前节点不是叶子节点,继续递归遍历 constructPaths(root.left, pathSB.toString(), paths); constructPaths(root.right, pathSB.toString(), paths); } } } }

时间复杂度更高 ,使用String+“ ”拼接字符串

class Solution { //这行代码可不敢写这里,leetcode提交会出问题的。。。。!!! //private static List<String> res = new ArrayList<String>(); public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<String>(); if(root == null)return res; BL(root,res,""); return res; } public static void BL(TreeNode node,List<String> res,String str){ if(node.left != null) BL(node.left, res, str + node.val + "->"); if(node.right != null) BL(node.right, res, str + node.val + "->"); if(node.left == null && node.right == null) res.add(str + node.val); } } 链接:https://leetcode-cn.com/problems/binary-tree-paths/solution/chang-gui-cao-zuo-50di-gui-by-gu-xiong-007/
2. BFS

时间复杂度:O(N2) 空间复杂度:O(N2)

class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> paths = new ArrayList<String>(); if (root == null) { return paths; } Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); Queue<String> pathQueue = new LinkedList<String>(); nodeQueue.offer(root); pathQueue.offer(Integer.toString(root.val)); while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.poll(); String path = pathQueue.poll(); if (node.left == null && node.right == null) { paths.add(path); } else { if (node.left != null) { nodeQueue.offer(node.left); pathQueue.offer(new StringBuffer(path).append("->").append(node.left.val).toString()); } if (node.right != null) { nodeQueue.offer(node.right); pathQueue.offer(new StringBuffer(path).append("->").append(node.right.val).toString()); } } } return paths; } }

【总结】

1. String StringBuffer StringBuilder
2.二叉树遍历
前序遍历 先输出当前结点的数据,再依次遍历输出左结点和右结点中序遍历 先遍历输出左结点,再输出当前结点的数据,再遍历输出右结点后续遍历 先遍历输出左结点,再遍历输出右结点,最后输出当前结点的数据
3.复制粘贴时候要小心 修改相应代码 脑子模拟代码 快速排查错误 多从自己写的代码 切忌浮躁

转载链接:https://leetcode-cn.com/problems/binary-tree-paths/solution/er-cha-shu-de-suo-you-lu-jing-by-leetcode-solution/ 参考链接:https://leetcode-cn.com/problems/binary-tree-paths/solution/chang-gui-cao-zuo-50di-gui-by-gu-xiong-007/

最新回复(0)