Inorder altaf

PHOTO EMBED

Thu Sep 14 2023 18:48:40 GMT+0000 (Coordinated Universal Time)

Saved by @Astik

#include <stdio.h>
#include <stdlib.h>

// Definition for a binary tree node
struct TreeNode {
    int val;
    struct TreeNode* left;
    struct TreeNode* right;
};

// Function to perform inorder traversal
void inorderTraversal(struct TreeNode* node) {
    // Base case: If the current node is null, return
    if (node == NULL) {
        return;
    }

    // Step 1: Recursively traverse the left subtree
    inorderTraversal(node->left);

    // Step 2: Visit (process) the current node
    // For example, print the value of the current node
    printf("%d ", node->val);

    // Step 3: Recursively traverse the right subtree
    inorderTraversal(node->right);
}

// Function to create a new node
struct TreeNode* newNode(int val) {
    struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    node->val = val;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Function to build a binary tree based on user input
struct TreeNode* buildTree() {
    int val;
    printf("Enter the root value: ");
    scanf("%d", &val);
    struct TreeNode* root = newNode(val);

    // Use a queue or a stack to maintain nodes to be processed
    // For simplicity, we'll use recursion for a small tree
    printf("Enter values for the left subtree (or -1 for no left child): ");
    scanf("%d", &val);
    if (val != -1) {
        root->left = buildTree();
    }

    printf("Enter values for the right subtree (or -1 for no right child): ");
    scanf("%d", &val);
    if (val != -1) {
        root->right = buildTree();
    }

    return root;
}

int main() {
    // Build a binary tree based on user input
    struct TreeNode* root = buildTree();

    // Perform inorder traversal
    printf("Inorder traversal: ");
    inorderTraversal(root);
    printf("\n");

    return 0;
}
content_copyCOPY