Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<string> BinaryTreePaths(TreeNode root) {
IList<string> paths = new List<string>();
if (root == null){
return paths;
}
IList<string> leftpaths = BinaryTreePaths(root.left);
IList<string> rightpaths = BinaryTreePaths(root.right);
foreach (string p in leftpaths){
paths.Add (root.val + "->" + p);
}
foreach (string p in rightpaths){
paths.Add (root.val + "->" + p);
}
if (paths.Count()==0){
paths.Add(root.val.ToString());
}
return paths;
}
}