Skip to main content

Inorder traversal of binary tree with recursion in c

C program for Inorder traversal of binary tree with recursion. Here problem description and explanation.

/*
  C Program 
  Inorder Tree Traversal of a Binary Tree
*/
#include <stdio.h>
#include <stdlib.h>

// Binary Tree node
struct TreeNode
{
    int data;
    struct TreeNode *left, *right;
};
// Binary Tree
struct BinaryTree
{
    struct TreeNode *root;
};
// Create new tree
struct BinaryTree *newTree()
{
    // Create dynamic node
    struct BinaryTree *tree = 
      (struct BinaryTree *) malloc(sizeof(struct BinaryTree));
    if (tree != NULL)
    {
        tree->root = NULL;
    }
    else
    {
        printf("Memory Overflow to Create tree Tree\n");
    }
    // Return new tree
    return tree;
}
// This is creating a binary tree node and return this
struct TreeNode *getNode(int data)
{
    // Create dynamic node
    struct TreeNode *node = 
      (struct TreeNode *) malloc(sizeof(struct TreeNode));
    if (node != NULL)
    {
        // Set data and pointer values
        node->data = data;
        node->left = NULL;
        node->right = NULL;
    }
    else
    {
        // This is indicates, segmentation fault or 
        // Memory overflow problem
        printf("Memory Overflow\n");
    }
    // Return new node
    return node;
}
// Recursive function
// Display Inorder view of binary tree
void inorder(struct TreeNode *node)
{
    if (node != NULL)
    {
        inorder(node->left);
        // Print node value
        printf("  %d", node->data);
        inorder(node->right);
    }
}
int main()
{
    struct BinaryTree *tree = newTree();
    /*
        Create Binary Tree
        -------------------
            15
           /  \
          24   54
         /    /  \
        35   62   13
    */
    // Add tree node
    tree->root = getNode(15);
    tree->root->left = getNode(24);
    tree->root->right = getNode(54);
    tree->root->right->right = getNode(13);
    tree->root->right->left = getNode(62);
    tree->root->left->left = getNode(35);
    // Display tree node
    inorder(tree->root);
    
    return 0;
}

Output

  35  24  15  62  54  13




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment