Welcome~~~


Another blog:
http://fun-st.blogspot.com/

It is easier to write an incorrect program than understand a correct one.

Monday, April 18, 2011

Printing expressions from Tree

http://www.daniweb.com/forums/thread323976.html

http://www.careercup.com/question?id=7473670

http://wordaligned.org/articles/python-surprise-me
http://openbookproject.net/thinkcs/python/english2e/ch21.html
http://stackoverflow.com/questions/1894846/printing-bfs-binary-tree-in-level-order-with-specific-formatting
http://codinggeeks.blogspot.com/2010/04/serializing-and-de-serializing-binary.html
http://ponywma.spaces.live.com/blog/cns!3757DF93DF1F3015!334.entry
 def printexp(tree):
    sVal=""
    if tree:
        sVal='( ' + printexp(tree.getLeft())
        sVal=sVal+str(tree.getRootValue())
        sVal= sVal+printexp(tree.getRight()) +' )'
    return sVal



Here is the source code and the text file format:
Note that the text file is created "by hand" and only read function is implemented in the code. Implementing write function should be straight forward.
==============================================
#include <stdio.h>

typedef struct tree_struct
{
int data;
int nchildren;
struct tree_struct *children;
}tree_t;

tree_t * create_new()
{
return ((tree_t *) malloc(sizeof(tree_t)));
}

int populate_tree(tree_t *root, FILE *fp)
{
fscanf(fp,"%d",&(root->nchildren));
root->children = NULL;

if(root->nchildren)
{
root->children = (tree_t *) malloc(root->nchildren * sizeof(tree_t));
for(int i=0; i<root->nchildren; i++)
fscanf(fp,"%d",&(root->children[i].data));
for(int i=0; i<root->nchildren; i++)
populate_tree(&root->children[i],fp);
}
else
return 0;
}

int print_tree(tree_t *root)
{
static int count = 0;
if(root)
{
if(!count++)
printf("%d\n",root->data);
if(root->nchildren)
{
for(int i=0; i<root->nchildren; i++)
printf("%d ",root->children[i].data);
printf("\n");
for(int i=0; i<root->nchildren; i++)
print_tree(&(root->children[i]));
}
return 0;
}
else
return -1;
}

int main(int argc, char *argv[])
{
char *filename = argv[1];
FILE *fp = fopen(filename,"r");
tree_t *root = create_new();

fscanf(fp, "%d", &(root->data));
populate_tree(root,fp);
print_tree(root);
}
==============================================
The tree taken for illustration purpose is:

5 ->3(1(4,19),7(20),2(25)), 10(11,17), 2(99,8)

The file format used is as follows:

<example.tree>
5
3 3 10 2
3 1 7 2
2 4 19
0
0
1 20
0
1 25
0
2 11 17
0
0
2 99 8
0
0
==============================================
To compile (on linux):
gcc -std=c99 -g main.c -o treeio
==============================================
Usage:
./treeio example.tree
Output:
5
3 10 2
1 7 2
4 19
20
25
11 17
99 8
==============================================

-- http://www.python-forum.org/pythonforum/viewtopic.php?f=14&t=5842

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

No comments:

Post a Comment