Question

How do I insert an unsorted array into a Binary Search Tree as a Doubly Linked...

How do I insert an unsorted array into a Binary Search Tree as a Doubly Linked List in C++?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <iostream>

#include <cstdlib>

using namespace std;

class BinarySearchTree

{

private:

struct tree_node

{

tree_node* left;

tree_node* right;

int data;

};

tree_node* root;

public:

BinarySearchTree()

{

root = NULL;

}

bool isEmpty() const { return root == NULL; }

void print_inorder();

void inorder(tree_node*);

void insert(int);

};

// Smaller elements go left

// larger elements go right

void BinarySearchTree::insert(int d)

{

tree_node* t = new tree_node;

tree_node* parent;

t->data = d;

t->left = NULL;

t->right = NULL;

parent = NULL;

// is this a new tree?

if (isEmpty()) root = t;

else

{

//Note: ALL insertions are as leaf nodes

tree_node* curr;

curr = root;

// Find the Node's parent

while (curr)

{

parent = curr;

if (t->data > curr->data) curr = curr->right;

else curr = curr->left;

}

if (t->data < parent->data)

parent->left = t;

else

parent->right = t;

}

}

void BinarySearchTree::print_inorder()

{

inorder(root);

}

void BinarySearchTree::inorder(tree_node* p)

{

if (p != NULL)

{

if (p->left) inorder(p->left);

cout << " " << p->data << " ";

if (p->right) inorder(p->right);

}

else return;

}

int main()

{

BinarySearchTree b;

int arr[] = {10,4,3,6,1,2};

cout << " Insertion/Creation " << endl;

for(int i= 0 ; i<6;++i)

b.insert(arr[i]);

cout << " Insertion Done " << endl;

cout << " In-Order Traversal " << endl;

b.print_inorder();

}




===========================
See Output


Thanks, PLEASE UPVOTE if helpful

Add a comment
Know the answer?
Add Answer to:
How do I insert an unsorted array into a Binary Search Tree as a Doubly Linked...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT