Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.0 kB
2
Indexable
Never
#include <stdio.h>
struct BinaryNode* createNode(char a);
struct BinaryNode* createExpressionTree();

struct BinaryNode{
    char data;
    struct BinaryNode* left; //left child
    struct BinaryNode* right; //right child
};
//(a + b * c) + ((d * e+f) * g)
main(){

    struct BinaryNode* root = createExpressionTree();

    //printf("%c ", root->data);
    //printf("%c ", root->left->data);
    //printf("%c ", root->right->data);

    //preorder
    preOrderTraversal(root);

}

void preOrderTraversal(struct BinaryNode* node){
    if(node == NULL) return;

    printf("%c", node->data);
    preOrderTraversal(node->left);
    preOrderTraversal(node->right);

}

struct BinaryNode* createExpressionTree(){
    struct BinaryNode* root = createNode('+');

    struct BinaryNode* node1 =  createNode('+');
    root->left = node1;

    struct BinaryNode* node2 =  createNode('a');
    node1->left = node2;

    struct BinaryNode* node3 =  createNode('*');
    node1->right = node3;

    struct BinaryNode* node4 =  createNode('b');
    node3->left = node4;

    struct BinaryNode* node5 =  createNode('c');
    node3->right = node5;

    struct BinaryNode* node6 =  createNode('*');
    root->right = node6;

    struct BinaryNode* node6left =  createNode('+');
    struct BinaryNode* node6right =  createNode('g');

    node6->left = node6left;
    node6->right = node6right;

    struct BinaryNode* node7left =  createNode('*');
    struct BinaryNode* node7right=  createNode('f');

    node6left->left = node7left;
    node6left->right = node7right;

    struct BinaryNode* node8left =  createNode('d');
    struct BinaryNode* node8right=  createNode('e');

    node7left->left = node8left;
    node7left->right = node8right;

    return root;
};

struct BinaryNode* createNode(char a){
    struct BinaryNode* node =  malloc(sizeof(struct BinaryNode));
    node->data = a;
    node->left = NULL;
    node->right = NULL;

    return node;
};

Leave a Comment