#K40957. Binary Tree Paths
Binary Tree Paths
Binary Tree Paths
Given a list of edges representing a binary tree, your task is to construct the binary tree and output all root-to-leaf paths. The tree is built by assigning the first available child as the left child and the second as the right child for each parent node. If the input list is empty, there is no output.
For example, given the edges:
1 2 1 3 2 4 3 5 3 6
The tree constructed is:
1 / \ 2 3 / / \ 4 5 6
And the output paths will be:
1->2->4 1->3->5 1->3->6
Note: In this problem, you are required to read the input from stdin and write the output to stdout using the specified format.
The underlying recurrence for the depth-first search (DFS) traversal can be described by the formula: \[ \text{paths}(node) = \begin{cases} \{\text{path} + node.val\} & \text{if } node \text{ is a leaf} \\ \text{paths}(node.left) \cup \text{paths}(node.right) & \text{otherwise} \end{cases} \]
inputFormat
The input begins with an integer n
representing the number of edges in the tree. The following n
lines each contain two integers, representing an edge from a parent node to a child node. If n
is 0, then the tree is empty.
Example:
5 1 2 1 3 2 4 3 5 3 6
outputFormat
Output each root-to-leaf path on a separate line. The nodes in the path should be concatenated using the '->' symbol.
Example Output:
1->2->4 1->3->5 1->3->6## sample
5
1 2
1 3
2 4
3 5
3 6
1->2->4
1->3->5
1->3->6
</p>