480. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
Example
Example 1:
Input:
1
/
2 3
5
Output:
[
"1->2->5",
"1->3"
]
Example 2:
Input:
1
/
2
Output:
[
"1->2"
]
注意:
因为题目的output格式 "1 -> 2",(有箭头),所以用String来存储每一个path。
递归法代码:
/** * 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 */ ArrayList<String> result; public List<String> binaryTreePaths(TreeNode root) { result = new ArrayList<String>(); if (root == null) { return result; } String path = String.valueOf(root.val); helper(root, path); return result; } public void helper(TreeNode root, String path) { if (root.left == null && root.right == null) { result.add(path); return; } if (root.left != null) { helper(root.left, path + "->" + String.valueOf(root.left.val)); } if (root.right != null) { helper(root.right, path + "->" + String.valueOf(root.right.val)); } } }