0% found this document useful (0 votes)
13 views3 pages

BST Insertion and Traversal

dsa

Uploaded by

adithyankollon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

BST Insertion and Traversal

dsa

Uploaded by

adithyankollon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Binary Search Tree inser on and traversal

#include <iostream>

#include<stdlib.h>

using namespace std;

// Define the structure of a tree node

struct TreeNode {

int data;

TreeNode* le ;

TreeNode* right;

}*temp,*newnode;

// Func on to insert a new node

TreeNode* insert(TreeNode* root, int value) {

newnode=(struct TreeNode*)malloc(sizeof(struct TreeNode));

newnode->data=value;

newnode->le =NULL;

newnode->right=NULL;

if (root == NULL) {

root=newnode;

return root;

if (value < root->data) {

root->le = insert(root->le , value);

else {

root->right = insert(root->right, value);

return root;

}
// In-order Traversal

void inOrderTraversal(TreeNode* root) {

if (root != NULL) {

inOrderTraversal(root->le );

cout << root->data << " ";

inOrderTraversal(root->right);

// Pre-order Traversal

void preOrderTraversal(TreeNode* root) {

if (root != NULL) {

cout << root->data << " ";

preOrderTraversal(root->le );

preOrderTraversal(root->right);

// Post-order Traversal

void postOrderTraversal(TreeNode* root) {

if (root != NULL) {

postOrderTraversal(root->le );

postOrderTraversal(root->right);

cout << root->data << " ";

int main() {

TreeNode* root = NULL;


// Insert values into the binary tree

root = insert(root, 50);

insert(root, 30);

insert(root, 70);

insert(root, 20);

insert(root, 40);

insert(root, 60);

insert(root, 80);

// Perform traversals

cout << "In-order Traversal: ";

inOrderTraversal(root);

cout << endl;

cout << "Pre-order Traversal: ";

preOrderTraversal(root);

cout << endl;

cout << "Post-order Traversal: ";

postOrderTraversal(root);

cout << endl;

return 0;

You might also like