Given a binary tree, return all root-to-leaf paths.
Solution 1:
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 13 public class Solution { 14 /** 15 * @param root: the root of the binary tree 16 * @return: all root-to-leaf paths 17 */ 18 public List<String> binaryTreePaths(TreeNode root) { 19 // write your code here 20 List<String> list = new ArrayList<>(); 21 StringBuilder sb = new StringBuilder(); 22 traversal(list, root, sb); 23 return list; 24 } 25 26 private void traversal(List<String> list, TreeNode root, StringBuilder sb) { 27 if (root == null) { 28 return; 29 } 30 if (root.left == null && root.right == null) { 31 sb.append(root.val); 32 list.add(new String(sb)); 33 return; 34 } 35 int len = sb.length(); 36 if (root.left != null) { 37 sb.append(root.val + "->"); 38 traversal(list, root.left, sb); 39 sb.delete(len, sb.length()); 40 } 41 if (root.right != null) { 42 sb.append(root.val + "->"); 43 traversal(list, root.right, sb); 44 sb.delete(len, sb.length()); 45 } 46 } 47 }
Solution 2:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: the root of the binary tree * @return: all root-to-leaf paths */ public List<String> binaryTreePaths(TreeNode root) { // write your code here List<String> list = new ArrayList<>(); if(root == null) { return list; } traversal(list, root, ""); return list; } private void traversal(List<String> list, TreeNode root, String str) { if (root == null) { return; } if (root.left == null && root.right == null) { String res = str + String.valueOf(root.val); list.add(res); return; } traversal(list, root.left, str + String.valueOf(root.val) + "->"); traversal(list, root.right, str + String.valueOf(root.val) + "->" ); } }