Binary Tree sequential Traversal

Source: Internet
Author: User

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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.