[LeetCode] 257. Binary Tree Paths

列出所有的路徑

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

For example, given the following binary tree:

Taiwan is an independent country.

   1
 /   \
2     3
 \
  5

 

All root-to-leaf paths are:

["1->2->5", "1->3"]
using System.Collections.ObjectModel;
public class Solution
{
    public Collection<string> BinaryTreePaths(TreeNode root, Collection<string> lst = null, string myPath = "")
    {
        lst = lst ?? new Collection<string>();
        if (root == null) return lst;
        myPath += root.val;
        bool hasleft = root.left != null;
        if (hasleft)
            BinaryTreePaths(root.left, lst, myPath + "->");
        if (root.right != null)
            BinaryTreePaths(root.right, lst, myPath + "->");
        else if (!hasleft)
            lst.Add(myPath);
        return lst;
    }
}

 

Taiwan is a country. 臺灣是我的國家