0% found this document useful (0 votes)
32 views

Comp 258: Assignment 2

The code sample provided finds the maximum element in a binary search tree using recursion. It defines a Node class to represent nodes in the binary search tree. The findMax method takes the root node as a parameter and recursively traverses the tree, keeping track of the maximum value encountered. It returns the maximum value by comparing the maximum of the left and right subtrees at each node. Base cases return the minimum integer value if a null node is reached. The main method builds a sample binary search tree and calls findMax to print the maximum element.

Uploaded by

Hamza Sheikh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Comp 258: Assignment 2

The code sample provided finds the maximum element in a binary search tree using recursion. It defines a Node class to represent nodes in the binary search tree. The findMax method takes the root node as a parameter and recursively traverses the tree, keeping track of the maximum value encountered. It returns the maximum value by comparing the maximum of the left and right subtrees at each node. Base cases return the minimum integer value if a null node is reached. The main method builds a sample binary search tree and calls findMax to print the maximum element.

Uploaded by

Hamza Sheikh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

COMP 258: ASSIGNMENT 2

Question 1

Advantages of generic data structures over non-generic data structures are:


Generics are the errors appearing are compile-time than at run-time. there are certain advantages of
generics over non-generic are as follows:

1. Code Reuse: With help of Generics, one needs to write a method/class/interface only once and
use it for any type whereas, in non-generics, the code needs to be written again and again whenever
needed. Java Generics helps the programmer to reuse the code for whatever type he/she wishes. For
instance, a programmer writes a generic method for sorting an array of objects. Generics allow the
programmer to use the same method for Integer arrays, Double arrays, and even String arrays.

2. Type Safety: Generics make errors to appear compile time than at run time (It’s always better to
know problems in your code at compile time rather than making your code fail at run time).
Suppose you want to create an ArrayList that store name of students and if by mistake the
programmer adds an integer object instead of a string, the compiler allows it. But, when we retrieve
this data from ArrayList, it causes problems at runtime.

3. Individual Type Casting is not needed: If we do not use generics, then, in the above example
every time we retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval
operation is a big headache. If we already know that our list only holds string data then we need not
typecast it every time.

4. Generics promotes code reusability.

5. Implementing generic algorithms: By using generics, we can implement algorithms that work
on different types of objects and at the same, they are type-safe too. It allows us to implement non-
generic algorithms.

Code that uses generics has many benefits over non-generic code:

 Stronger type checks at compile time.


 A Java compiler applies strong type checking to generic code and issues errors if the code
violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which
can be difficult to find.
 Elimination of casts.
 The following code snippet without generics requires casting:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);
 When re-written to use generics, the code does not require casting:
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0); // no cast
 Enabling programmers to implement generic algorithms.
 By using generics, programmers can implement generic algorithms that work on collections
of different types, can be customized, and are type-safe and easier to read.

Question 2
a) Given the following list of numbers: 50, 25, 75, 13, 33, 60, 88, 7, 19, 80, 101. Create a
graphic displaying the tree these numbers were inserted into a binary search tree in
the order above.

Java Code:

package binarysearchtree;

// Java program to print BST according to the given list of numbers

// A binary tree node

class Node {

int data;
Node left, right;

Node(int d) {
data = d;
left = right = null;
}
}

public class BinarySearchTree {

static Node root;

/* A function that constructs Balanced Binary Search Tree from a sorted array */

Node sortedArrayToBST(int arr[], int start, int end) {

/* Base Case */
if (start > end) {
return null;
}

/* Get the middle element and make it root */


int mid = (start + end) / 2;
Node node = new Node(arr[mid]);

/* Recursively construct the left subtree and make it left child of root */
node.left = sortedArrayToBST(arr, start, mid - 1);

/* Recursively construct the right subtree and make it right child of root */
node.right = sortedArrayToBST(arr, mid + 1, end);

return node;
}

/* A utility function to print preorder traversal of BST */


void preOrder(Node node) {
if (node == null) {
return;
}
System.out.print(node.data + " ");
preOrder(node.left);
preOrder(node.right);
}

public static void main(String[] args) {


BinarySearchTree tree = new BinarySearchTree();
int arr[] = new int[]{75, 13, 25, 33, 60, 50, 7, 19, 88, 80, 101};
int n = arr.length;
root = tree.sortedArrayToBST(arr, 0, n - 1);
System.out.println("Preorder traversal of constructed BST according to the given list of
numbers is: " + "\n");
tree.preOrder(root);
}
}

Output:
b) Do you consider the tree to be an efficiently structured tree? If yes, provide a
sequence that would create an inefficiently structured tree.

The idea of a binary search tree is that data is stored according to order so that it can be
retrieved very efficiently. By creating the Binary Search Tree according to the given list of
numbers and properly using the appropriate data structure, we consider it to be an efficiently
structured tree. Now, for creating the inefficiently structured Binary Search Tree one should
follow the sequence of creating an unbalanced Binary Search Tree using an unsorted array
data structure because the moment when a binary tree becomes unbalanced, it loses its
efficiency. Based on everything that we already know about binary search trees, we know
that they are incredibly powerful because of their logarithmic runtime, which is exactly
what makes them so fast and efficient.

Question 3

Describe the two features required for a recursive method. When does a recursive
method behave like an infinite loop?
In recursion, the recursive function calls itself repeatedly until a base condition is satisfied. The memory
for the called function is pushed onto the stack at the top of the memory for the calling function. For
each function call, a separate copy of local variables is made.

Any method that implements Recursion has two required features:

 Method calls which can call themselves i.e. recursive


 A precondition that will stop the recursion.

The general syntax of recursion is as follows:

methodName (T parameters…)
{
if (precondition == true)
//precondition or base condition
{
return result;
}
return methodName (T parameters…);
//recursive call
}

The precondition is also called the base condition. The basic idea behind using recursion is to express
the bigger problem in terms of smaller problems. Also, we need to add one or more base conditions so
that we can come out of recursion.

Note that a precondition or a base condition is necessary for any recursive method as in the case if we do
not break the recursion then it will keep on running infinitely (behave like an infinite loop) and result in
a stack overflow.

Question 4

// Java code to Find a maximum element in Binary Search Tree:

package binarysearchtree;

// A binary tree node


class Node {
int data;
Node left, right;

public Node(int data)


{
this.data = data;
left = right = null;
}
}

class BinarySearchTree {
Node root;

// Returns the max value in a binary search tree


static int findMax(Node node)
{
if (node == null)
return Integer.MIN_VALUE;

int res = node.data;


int lres = findMax(node.left);
int rres = findMax(node.right);

if (lres > res)


res = lres;

if (rres > res)


res = rres;

return res;
}
public static void main(String args[])
{
BinarySearchTree tree = new BinarySearchTree();
tree.root = new Node(50);
tree.root.left = new Node(25);
tree.root.left.right = new Node(75);
tree.root.left.right.left = new Node(13);
tree.root.left.right.right = new Node(33);
tree.root.left.right.left = new Node(60);
tree.root.right = new Node(88);
tree.root.right.left = new Node(7);
tree.root.right.right = new Node(19);
tree.root.right.right.left = new Node(80);
tree.root.right.right.right = new Node(101);

// Function call
System.out.println("Maximum element of the Tree is: "
+ tree.findMax(tree.root));
}
}

Output:

References:
https://docs.oracle.com/javase/tutorial/java/generics/why.html

You might also like