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
private List<string> list = new List<string>();
public IList<string> BinaryTreePaths(TreeNode root)
{
if (root == null)
{
return list;
}
else
{
Chuck(string.Empty, root);
}
return list;
}
private void Chuck(string str, TreeNode node)
{
if (node == null)
{
return;
}
if (str.Equals(string.Empty))
{
str = $"{node.val}";
}
else
{
str = $"{str}->{node.val}";
}
if (node.left == null && node.right == null)
{
list.Add(str);
}
else
{
Chuck(str, node.left);
Chuck(str, node.right);
}
}
Runtime: 264 ms, faster than 53.41% of C# online submissions for Binary Tree Paths.
Memory Usage: 30 MB, less than 24.53% of C# online submissions forBinary Tree Paths.