Data structure basic exercise-binary tree image

Source: Internet
Author: User
Description:

Input a binary tree and output its image.

Input:

The input may contain multiple test examples. The input ends with EOF.
For each test case, the first input behavior is an integer N (0 <=n <= 1000, and N represents the number of Binary Tree nodes to be input (nodes start from 1 ). The next row contains N numbers, representing the value of the element of the I-th Binary Tree node. Next there are n rows, each row has a letter CI.
Ci = 'D' indicates that the I node has two children, followed by the left and right children numbers.
Ci = 'l' indicates that the I node has a left child followed by the ID of the left child.
Ci = 'R' indicates that the I node has a right child followed by the number of the right child.
Ci = 'Z' indicates that no child exists on the I node.

Output:

Corresponding to each test case,
Output the element values of the child node in the forward order.
If it is null, the output is null.

Sample input:
78 6 10 5 7 9 11d 2 3d 4 5d 6 7zzzz
Sample output:
8 10 11 9 6 7 5

The idea is simple. Just simulate it again. Tree Structure is unnecessary. when outputting data, you can first right and then left.

#include <stdio.h>int n, a, i;typedef struct Node {struct Node * l;struct Node * r;int data;}* pNode, Node;char temp[2];Node tree[1001];void print(pNode root) {if (root == 0)return;printf(" %d", root->data);print(root->r);print(root->l);}int main() {while (~scanf("%d", &n)) {for ( i = 1; i <= n; i++) {scanf("%d", &tree[i].data);tree[i].l = tree[i].r = 0;}for ( i = 1; i <= n; i++) {scanf("%s %d", temp, &a);if (temp[0] == 'd') {tree[i].l = &tree[a];scanf("%d", &a);tree[i].r = &tree[a];}else if(temp[0] == 'l')tree[i].l = &tree[a];else if(temp[0] == 'r')tree[i].r = &tree[a];}if (n) {printf("%d", tree[1].data);print(tree[1].r);print(tree[1].l);puts("");} elseputs("NULL");}return 0;}

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.