1. 程式人生 > 其它 >[LintCode] 480. Binary Tree Paths

[LintCode] 480. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

 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 }