I'm just trying to create a binary tree, and a pretty printer for it:
#include <stdio.h>
typedef unsigned long Leaf;
struct NodeStruct {
struct TreeStruct * left;
struct TreeStruct * right;
};
typedef struct NodeStruct Node;
struct TreeStruct {
char isNode;
union {
Node node;
Leaf leaf;
} value;
};
typedef struct TreeStruct Tree;
Tree node(Tree* left, Tree* right){
Tree result;
result.isNode = 1;
result.value.node.left = left;
result.value.node.right = right;
return result;
};
Tree leaf(unsigned long x){
Tree result;
result.isNode = 0;
result.value.leaf = x;
return result;
};
void print(Tree* tree, int isRoot){
if (!tree->isNode){
printf("%lu",tree->value.leaf);
return;
};
printf("(");
print(tree->value.node.left,0);
printf(" ");
print(tree->value.node.right,0);
printf(")");
};
int main(){
Tree a = leaf(1);
Tree b = leaf(2);
Tree c = leaf(3);
Tree d = leaf(4);
Tree ab = node(&a,&b);
Tree cd = node(&c,&d);
Tree abcd = node(&ab,&cd);
print(&abcd,1);
};
There are so many things that sound wrong to me, yet I don't know how I'm supposed to improve this in C. Ideas?
Also, what if I wanted to return the string instead of printing it?