Aizu ALDS1_7_C Tree Walk

来源:互联网 发布:录制游戏的软件 编辑:程序博客网 时间:2024/06/05 16:22

Tree - Tree Walk

Time Limit : 1 sec, Memory Limit : 65536 KB 
Japanese version is here

Tree Walk

Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either

  • contains no nodes, or
  • is composed of three disjoint sets of nodes:
    - a root node.
    - a binary tree called its left subtree.
    - a binary tree called its right subtree.

Your task is to write a program which perform tree walks (systematically traverse all nodes in a tree) based on the following algorithms:

  1. Print the root, the left subtree and right subtree (preorder).
  2. Print the left subtree, the root and right subtree (inorder).
  3. Print the left subtree, right subtree and the root (postorder).

Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n linen, the information of each node is given in the following format:

id left right

id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1

Output

In the 1st line, print "Preorder", and in the 2nd line print a list of node IDs obtained by the preorder tree walk.

In the 3rd line, print "Inorder", and in the 4th line print a list of node IDs obtained by the inorder tree walk.

In the 5th line, print "Postorder", and in the 6th line print a list of node IDs obtained by the postorder tree walk.

Print a space character before each node ID.

Constraints

  • 1 ≤ n ≤ 25

Sample Input 1

90 1 41 2 32 -1 -13 -1 -14 5 85 6 76 -1 -17 -1 -18 -1 -1

Sample Output 1

Preorder 0 1 2 3 4 5 6 7 8Inorder 2 1 3 0 6 5 7 4 8Postorder 2 3 1 6 7 5 8 4 0

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


 
题目大意:输出一个树的前中后序遍历

#include<iostream>#include<cstdio>using namespace std;#define NIL -1struct Node{int parent;int left;int right;}tree[30];int n;void init(){for(int i=0;i<n;i++){tree[i].parent=NIL;}}void Preorder(int root){if(root==NIL) return;cout<<' '<<root;Preorder(tree[root].left);Preorder(tree[root].right);}void Inorder(int root){if(root==NIL) return;Inorder(tree[root].left);cout<<' '<<root;Inorder(tree[root].right);}void Postorder(int root){if(root==NIL) return;Postorder(tree[root].left);Postorder(tree[root].right);cout<<' '<<root;}int main(){cin>>n;init();for(int i=0;i<n;i++){int node_index;int l,r;cin>>node_index>>l>>r;tree[node_index].left=l;tree[node_index].right=r;if(l!=NIL) tree[l].parent=node_index;if(r!=NIL) tree[r].parent=node_index;}int root;for(int i=0;i<n;i++){if(tree[i].parent==NIL){root=i;}}cout<<"Preorder"<<endl;Preorder(root);cout<<endl;cout<<"Inorder"<<endl;Inorder(root);cout<<endl;cout<<"Postorder"<<endl;Postorder(root);cout<<endl;}



原创粉丝点击