Given a binary tree, return all root-to-leaf paths.
Note
A leaf is a node with no children.
Example
Input:
Output: [“1->2->5”, “1->3”]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
Code
1 2 3 4 5 6
|
public class { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
public List<String> binaryTreePaths(TreeNode root) { List<String> result = new ArrayList<>();
if (root == null) return result;
StringBuilder sb = new StringBuilder(); helper(result, root, sb.append(root.val)); return result; }
private void helper(List<String> result, TreeNode root, StringBuilder sb) { if (root.left == null && root.right == null) { result.add(sb.toString()); return; }
int length = sb.length();
if (root.left != null) { helper(result, root.left, sb.append("->").append(root.left.val)); sb.setLength(length); } if (root.right != null) { helper(result, root.right, sb.append("->").append(root.right.val)); sb.setLength(length); } }
|
近期评论