Binary Tree Paths
Easy · tree dfs
You are given the root of a binary tree. A leaf is a node with no children. Return every path that starts at the root and ends at a leaf, each one written as a string.
Write a path by listing the values of its nodes from the root downwards, joined with -> and no spaces. For example, a path through nodes with values 1, 2 and 5 is "1->2->5", and a negative value is written with its minus sign, as in "4->-3".
List the paths from left to right: a path that goes through a node's left child comes before any path that goes through its right child. A tree with a single node has one path, just that node's value. An empty tree has no paths, so return an empty list.
Examples
Example 1
Input: root = [1, 2, 3, null, 5]
Output: ["1->2->5", "1->3"]
Node 2 is not a leaf because it has the child 5, so the leaves are 5 and 3, in that left-to-right order.
Example 2
Input: root = [7]
Output: ["7"]
A lone root is also a leaf.
Example 3
Input: root = [4, -3, 2, null, null, 1]
Output: ["4->-3", "4->2->1"]
Constraints
- The number of nodes is in the range [0, 100].
- -100 <= Node.val <= 100