Bin Tree Implementation

mail@pastecode.io avatar
unknown
c_cpp
6 months ago
1.2 kB
2
Indexable
Never
//
// Created by Luka on 5.10.2023..
//

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

struct Node {
    int val;
    struct Node* left;
    struct Node* right;
};

struct Node* newNode(int val) {
    struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
    newNode->val   = val;
    newNode->left  = NULL;
    newNode->right = NULL;

    return newNode;
}

void insertNode(struct Node* currNode, int val) {
    if (val <= currNode->val) {
        if (currNode->left != NULL) {
            insertNode(currNode->left, val);
        }
        else {
            currNode->left = newNode(val);
        }
    }
    else {
        if (currNode->right != NULL) {
            insertNode(currNode->right, val);
        }
        else {
            currNode->right = newNode(val);
        }
    }
}

void traverse(struct Node* currNode) {
    if (currNode == NULL)
        return;
    traverse(currNode->left);
    printf("%d\n", currNode->val);
    traverse(currNode->right);
}

int main() {
    struct Node *root = newNode(0);

    insertNode(root, 3);
    insertNode(root, 1);
    insertNode(root, -10);
    insertNode(root, -5);

    traverse(root);

    return 0;
}