0% found this document useful (0 votes)
16 views4 pages

Computer Science & Engineering: Department of

java codes

Uploaded by

Akshat Sharma
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)
16 views4 pages

Computer Science & Engineering: Department of

java codes

Uploaded by

Akshat Sharma
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/ 4

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


Experiment 2.2

Aim: To implement the concept of Tree Data Structure.

Objective: To get the required output as per the statement of problem.

Q1: You are given a pointer to the root of a binary search tree and values
to be inserted into the tree. Insert the values into their appropriate position
in the binary search tree and return the root of the updated binary tree. You
just have to complete the function.

Algorithm:
insert(node, key)

i) If root == NULL,
return the new node to the calling function.
ii) if root=>data < key
call the insert function with root=>right and assign the return value in root=>right.
root->right = insert(root=>right,key)
iii) if root=>data > key
call the insert function with root->left and assign the return value in root=>left.
root=>left = insert(root=>left,key)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Code:
Node * insert(Node * root, int data) {if(root==NULL){
Node* n = new Node(data);root = n;
}
if(root->data < data){
root->right = insert(root-
>right,data);
}
if(root->data > data){
root->left = insert(root->left,data);
}

return root;
}

Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Q2: In this challenge, you are required to implement inorder traversal of a


tree.
Complete the inOrder function in your editor below, which has 1
parameter: a pointer to the root of a binary tree. It must print the values in
the tree's inorder traversal as a single line ofspace-separated values.

Algorithm:
Traverse the left subtree, i.e., call Inorder(left->subtree) Visit
the root.
Traverse the right subtree, i.e., call Inorder(right->subtree)

Code:
void inOrder(Node *root) {
if(root==NULL){
return;
}
inOrder(root->left); cout<<root-
>data<<" ";inOrder(root-
>right);}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Output:

Learning Outcomes:
a. I have learned about the tree creation.
b. I have learned about the BST.
c. I have learned about the inorder traversal.

You might also like