#C13658. Post-order Traversal of a Binary Tree

    ID: 43220 Type: Default 1000ms 256MiB

Post-order Traversal of a Binary Tree

Post-order Traversal of a Binary Tree

You are given a binary tree represented in a specific format. Each node in the tree is described by its value along with the indices of its left and right children. The tree is provided as follows:

  • The first line contains an integer n denoting the number of nodes in the tree.
  • The following n lines each contain a node description with three values: a string value, an integer left, and an integer right. Here, left and right are the indices (0-indexed) of the left and right children respectively. If a child is missing, the corresponding index will be -1.

The root of the tree is always the node at index 0. Your task is to perform a post-order traversal of the binary tree and return the concatenated string of node values visited in that order.

Recall: The post-order traversal of a binary tree is defined recursively as follows:

[ \text{postorder}(node) = \text{postorder}(left,child) ; + ; \text{postorder}(right,child) ; + ; \text{value}(node) ]

For example, consider the following binary tree:

7
A 1 2
B 3 4
C 5 6
D -1 -1
E -1 -1
F -1 -1
G -1 -1

The corresponding tree structure is:

         A
        / \
       B   C
      / \ / \
     D  E F  G

The post-order traversal will produce: DEBFGCA.

inputFormat

The input is read from standard input (stdin) and has the following format:

  1. The first line contains an integer n representing the number of nodes in the tree.
  2. Each of the next n lines contains three items separated by spaces: a string (the value of the node), an integer representing the index of the left child, and an integer representing the index of the right child. A value of -1 indicates that the child is missing.

It is guaranteed that the node at index 0 is the root of the tree.

outputFormat

Output a single line to standard output (stdout), which is the concatenated string of node values obtained by performing a post-order traversal of the given binary tree.

## sample
7
A 1 2
B 3 4
C 5 6
D -1 -1
E -1 -1
F -1 -1
G -1 -1
DEBFGCA