Computer Science & Engineering: Department of
Computer Science & Engineering: Department of
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
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.