Binary tree
unknown
c_cpp
2 years ago
1.4 kB
4
Indexable
#include <stdio.h> #include <stdlib.h> // define the binary tree node structure struct node { int data; struct node* left; struct node* right; }; // function to create a new node with the given data struct node* new_node(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return node; } // function to insert a new node with the given data into the binary tree struct node* insert(struct node* node, int data) { if (node == NULL) { return new_node(data); } else { if (data <= node->data) { node->left = insert(node->left, data); } else { node->right = insert(node->right, data); } return node; } } // function to traverse the binary tree in-order and print the values void inorder_traversal(struct node* node) { if (node != NULL) { inorder_traversal(node->left); printf("%d ", node->data); inorder_traversal(node->right); } } // main function int main() { struct node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); printf("In-order traversal of the binary tree: "); inorder_traversal(root); return 0; }