Binary Tree sequential Traversal
Description
Returns the forward and backward traversal of a binary tree.
Input/Output Format
Input description:
The first line is an integer n, indicating the number of nodes in the tree.
The next n rows have two integers (L and R) in each row. The two integers Li and Ri in line I represent the left Son Number and the right son number of the node numbered I.
Output description:
The output consists of three rows, namely, forward traversal, central traversal, and backward traversal. Numbers are separated by spaces.
Input and Output sample
Input example #1:
5
2 3
4 5
0 0
0 0
0 0
Output sample #1:
1 2 4 5 3
4 2 5 1 3
4 5 2 3 1
Ideas
Recursion. First write the first order, then slightly change the first order, copy and paste it three times.
Code # include <stdio. h> int a [100], B [100]; void A (int I) {printf ("% d", I); if (a [I]) A (a [I]); if (B [I]) A (B [I]);} void B (int I) {if (a [I]) B (a [I]); printf ("% d", I); if (B [I]) B (B [I]);} void C (int I) {if (a [I]) C (a [I]); if (B [I]) C (B [I]); printf ("% d ", i) ;}int main () {int n, I; scanf ("% d", & n); for (I = 1; I <= n; I ++) scanf ("% d", & a [I], & B [I]); A (1); printf ("\ n"); B (1 ); printf ("\ n"); C (1); return 0;} View Code