Root-to-Leaf Paths as Strings
Problem statement
You are given the root of a binary tree. A leaf is a node with no children.
For every leaf, write the path from the root down to that leaf as one string: the node values in order, joined by "->". For example, the path through values 1, -2 and 5 is "1->-2->5".
Return all the path strings, one per leaf, ordered by leaf from left to right. This is the order in which a walk that always finishes a node's left subtree before its right subtree reaches the leaves.
Function
rootToLeafPaths(root: TreeNode) → List<String>Examples
Example 1
root = [4,9,0,5,1]return = ["4->9->5","4->9->1","4->0"]The leaves are 5, 1 and 0, from left to right. Reading from the root down to each of them gives "4->9->5", "4->9->1" and "4->0", in that order.
Example 2
root = [7,null,-2,3]return = ["7->-2->3"]The root 7 has only a right child -2, whose only child is 3. Nodes with one child are not leaves, so there is one path, "7->-2->3". A negative value keeps its minus sign.
Example 3
root = [8]return = ["8"]The root has no children, so it is a leaf on its own and its path is just "8".
Constraints
- The tree has between
1and500nodes. -100 <= node.val <= 100- The tree does not have to be balanced. It can be a single chain of
500nodes.