CorrctionDS Review AlgoComplexity

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Correction

Exercise 1

1. d) O(n^2)
2. c) O(n)
3. b) O(log n)
4. d) O(n^2)
5. c) O(n)
6. b) It represents the scenario where the algorithm performs best.
7. Write a Java program to perform Selection Sort on an array of strings in alphabetical
order. What is the complexity of this algo in the worst case and best case ?
Exercise 2

1. Insert method code and time complexity:

class BinaryTree {
Node root;

// Insert method to insert a new node with given data


public void insert(int data) {
root = insertRec(root, data);
}

// Recursive method to insert a new node with given data


private Node insertRec(Node root, int data) {
// If the tree is empty, create a new node
if (root == null) {
root = new Node(data);
return root;
}

// Otherwise, recur down the tree


if (data < root.data)
root.left = insertRec(root.left, data);
else if (data > root.data)
root.right = insertRec(root.right, data);

// Return the (unchanged) node pointer


return root;
}
}

The time complexity of the insertion operation in a binary search tree is O(h), where h is the
height of the tree. In the worst-case scenario, when the tree is skewed (unbalanced), the height of
the tree can be equal to the number of nodes, resulting in a time complexity of O(n). However, in
a balanced binary search tree, the height is usually log(n), where n is the number of nodes,
resulting in an average time complexity of O(log n).
2. Height method code:

class BinaryTree {
Node root;

// Method to find the height of the binary search tree


public int height() {
return heightRec(root);
}

// Recursive method to find the height of the binary search tree


private int heightRec(Node root) {
// Base case: if the tree is empty
if (root == null)
return 0;

// Recursively find the height of the left and right subtrees


int leftHeight = heightRec(root.left);
int rightHeight = heightRec(root.right);

// Return the maximum of the heights of the left and right subtrees,
plus 1 for the current node
return Math.max(leftHeight, rightHeight) + 1;
}
}

3. isBST method code:

java
class BinaryTree {
Node root;

// Method to check if a binary tree is a binary search tree


public boolean isBST() {
return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

// Utility method to check if a binary tree is a binary search tree


private boolean isBSTUtil(Node root, int min, int max) {
// Base case: if the tree is empty
if (root == null)
return true;

// Check if the current node's data is within the valid range


if (root.data < min || root.data > max)
return false;

// Recursively check the left and right subtrees with updated range
limits
return isBSTUtil(root.left, min, root.data - 1) &&
isBSTUtil(root.right, root.data + 1, max);
}
}

You might also like