Eukleides project

from http://d.hatena.ne.jp/u5_h/

(構造関連)binarytree(いつかの課題で出たやつ)

図の2分木(Binary Tree)をプログラムより表述し、前順(preoder)、間順(inorder)、後順(postorder) で辿って下記のような実行結果を表示するプログラム

#include
#include

struct node {
char element;
struct node *left;
struct node *right;
};

void preorder(struct node *);
void inorder(struct node *);
void postorder(struct node *);

int main(void)
{
struct node *root;
root=(struct node *)malloc(sizeof(struct node));
root->right=(struct node *)malloc(sizeof(struct node));
root->left=(struct node *)malloc(sizeof(struct node));
root->left->right=(struct node *)malloc(sizeof(struct node));
root->left->left=(struct node *)malloc(sizeof(struct node));
root->right->left=(struct node *)malloc(sizeof(struct node));
root->right->right=(struct node *)malloc(sizeof(struct node));
root->right->right->left=(struct node *)malloc(sizeof(struct node));
root->right->right->right=(struct node *)malloc(sizeof(struct node));

root->left->right->left=NULL;
root->left->right->right=NULL;
root->left->left->right=NULL;
root->left->left->left=NULL;
root->right->left->right=NULL;
root->right->left->left=NULL;
root->right->right->left->left=NULL;
root->right->right->left->right=NULL;
root->right->right->right->right=NULL;
root->right->right->right->left=NULL;


root->element='*';
root->right->element='-';
root->left->element='+';
root->left->right->element='b';
root->left->left->element='a';
root->right->left->element='c';
root->right->right->element='/';
root->right->right->left->element='d';
root->right->right->right->element='e';

printf("prefix notation ===>");
preorder(root);
printf("\n infix notation ===>");
inorder(root);
printf("\n postfix notation ===>");
postorder(root);
putchar('\n');
printf("***** END OF TRAVERSAL *****\n");

return 0;

}

void preorder(struct node *p)
{
if(p!=NULL)
{
printf(" %c",p->element);
preorder(p->left);
preorder(p->right);
}
}
void inorder(struct node *p)
{
if(p!=NULL)
{
inorder(p->left);
printf(" %c",p->element);
inorder(p->right);
}
}

void postorder(struct node *p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf(" %c",p->element);
}
}
/*Makefile
CFIAGS= -g
binarytree:*/

実行結果
Current directory is ~/c_language_execise/
GNU gdb 6.3.50_2004-12-28-cvs (cygwin-special)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i686-pc-cygwin"...
(gdb) r
Starting program: /home/yugo/c_language_execise/binarytree.exe
prefix notation ===> * + a b - c / d e
infix notation ===> a + b * c - d / e
postfix notation ===> a b + c d e / - *

**** END OF TRAVERSAL *****

Program exited normally.