Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list=new ArrayList();
if(root==null)
return list;
if(root.left==null&&root.right==null)
list.add(root.val+"");
List<String> left=binaryTreePaths(root.left);
for(String s:left)
list.add(root.val+"->"+s);
List<String> right=binaryTreePaths(root.right);
for(String s:right)
list.add(root.val+"->"+s);
return list;
}
}