Binary Tree and all traversals

#include <stdio.h>
#include <malloc.h>
typedef struct node
{
    int data;
    struct node *left;
    struct node *right;
node;
node *create()
{
    node *p;
    int x;
    printf("Enter data(-1 for no data):");
    scanf("%d", &x);
    if (x == -1)
        return NULL;
    p = (node *)malloc(sizeof(node));
    p->data = x;
    printf("Enter left child of %d:\n"x);
    p->left = create();
    printf("Enter right child of %d:\n"x);
    p->right = create();
    return p;
}
void preorder(node *t)
{
    if (t != NULL)
    {
        printf("%d "t->data);
        preorder(t->left);
        preorder(t->right);
    }
}
void postorder(node *t)
{
    if (t != NULL)
    {
        postorder(t->left);
        postorder(t->right);
        printf("%d "t->data);
    }
}
void inorder(node *t)
{
    if (t != NULL)
    {
        inorder(t->left);
        printf("%d "t->data);
        inorder(t->right);
    }
}
int main()
{
    node *root;
    root = create();
    printf("\nThe preorder traversal of tree is:\n");
    preorder(root);
    printf("\nThe inorder traversal of tree is:\n");
    inorder(root);
    printf("\nThe postorder traversal of tree is:\n");
    postorder(root);
    return 0;
}

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree