BFS解,时间O(n^2),空间O(n^2)
1 public List<String> binaryTreePaths(TreeNode root) { 2 List<String> paths = new ArrayList<String>(); 3 if(root==null) return paths; 4 Queue<TreeNode> queue1 = new LinkedList<TreeNode>(); 5 Queue<String> queue2 = new LinkedList<String>(); 6 queue1.add(root); 7 queue2.add(Integer.toString(root.val)); 8 while(!queue1.isEmpty()){ 9 TreeNode temp = queue1.poll(); 10 String path = queue2.poll(); 11 if(temp.left==null && temp.right==null){ 12 paths.add(path); 13 continue; 14 } 15 if(temp.left!=null){ 16 queue1.add(temp.left); 17 queue2.add(new StringBuilder(path).append("->"+temp.left.val).toString()); 18 } 19 if(temp.right!=null){ 20 queue1.add(temp.right); 21 queue2.add(new StringBuilder(path).append("->"+temp.right.val).toString()); 22 } 23 } 24 return paths; 25 }