时间复杂度: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/时间复杂度: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; } }转载链接: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/