Question

In: Computer Science

Recursion java: 1. Write a recursive algorithm to add all the elements of an array of...

Recursion java:

1. Write a recursive algorithm to add all the elements of an array of n elements

2. Write a recursive algorithm to get the minimum element of an array of n elements

3. Write a recursive algorithm to add the corresponding elements of two arrays (A and B) of n elements. Store the results in a third array C

.4. Write a recursive algorithm to get the maximum element of a binary tree

5. Write a recursive algorithm to get the number of elements of a binary tree

Solutions

Expert Solution

1. Recursive algorithm to add elements of an array:

// ArraySum.java
import java.util.Scanner;
public class ArraySum
{
    static int findSum(int array[], int n){
        if(n<=0)
            return 0;
        return (findSum(array, n-1) + array[n-1]);
    }
        public static void main(String[] args) {
            System.out.println("Enter number of elements: ");
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int array[] = new int[n];
            System.out.println("Enter elements:");
            for(int i=0; i<n; i++)
                array[i] = sc.nextInt();
           int sum = findSum(array, n);
            System.out.println("Sum of array elements: " + sum);
        }
}

Output:

Enter number of elements:                                      
5                                                              
Enter elements:                                                
1 2 3 4 5                                                         
Sum of array elements: 15

2. Recursive algorithm to get the minimum element of an array:

// ArrayMinimum.java
import java.util.Scanner;
public class ArrayMinimum
{
    static int findMin(int array[], int n){
        if(n==1)
            return array[0];
        return Math.min(array[n-1], findMin(array, n-1));
    }
        public static void main(String[] args) {
            System.out.println("Enter number of elements: ");
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int array[] = new int[n];
            System.out.println("Enter elements:");
            for(int i=0; i<n; i++)
                array[i] = sc.nextInt();
           int min = findMin(array, n);
            System.out.println("Min of array elements: " + min);
        }
}

Output:

Enter number of elements:                                      
3                                                              
Enter elements:                                                
22 -30 10                                                            
Min of array elements: -30  

3. Recursive algorithm to add the corresponding elements of two arrays and store them in third array.

// ArraySum.java
import java.util.Scanner;
public class ArraySum
{
    static int[] findSum(int[] A, int[] B, int[] C, int n){
        if(n<=0)
            return C;
        C[n-1] = A[n-1] + B[n-1];
        return findSum(A, B, C, n-1);
    }
        public static void main(String[] args) {
            System.out.println("Enter number of elements: ");
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int A[] = new int[n];
            int B[] = new int[n];
            System.out.println("Enter elements of first array:");
            for(int i=0; i<n; i++)
                A[i] = sc.nextInt();
            System.out.println("Enter elements of second array:");
            for(int i=0; i<n; i++)
                B[i] = sc.nextInt();
            int C[] = new int[n];
            findSum(A, B, C, n);
            System.out.println("Sum Array:");
            for(int i=0; i<n; i++)
                System.out.print(C[i] + " ");
        }
}

Output:

Enter number of elements:                                                                                                     
5                                                                                                                             
Enter elements of first array:                                                                                                
1 2 3 4 5                                                                                                                     
Enter elements of second array:                                                                                               
1 2 3 4 5                                                                                                                     
Sum Array:                                                                                                                    
2 4 6 8 10

4. Recursive program to find the minimum element of binary tree.

// BinaryTreeMaximum.java
class Node{
    int data;
    Node left, right;
    public Node(int data){
        this.data = data;
        left = right = null;
    }
}
class BinaryTree{
    Node root;
    static int findMax(Node node){
        if(node == null)
            return Integer.MIN_VALUE;
        int res = node.data;
        int l = findMax(node.left);
        int r = findMax(node.right);
        if(l>r)
            res = l;
        if(r>res)
            res = r;
        return res;
    }
}
public class BinaryTreeMaximum
{
        public static void main(String[] args) {
            BinaryTree t = new BinaryTree();
            t.root = new Node(10);
            t.root.left = new Node(25);
            t.root.right = new Node(30);
            t.root.left.left = new Node(50);
            t.root.left.right = new Node(45);
            System.out.println("Maximum element in binary tree: " + t.findMax(t.root));
        }
}

Output:

Maximum element in binary tree: 50

5. Recursive program to find the number of elements in binary tree.

// BinaryTreeElements.java
class Node{
    int data;
    Node left, right;
    public Node(int data){
        this.data = data;
        left = right = null;
    }
}
class BinaryTree{
    Node root;
    int size(){
        return size(root);
    }
    int size(Node node){
        if(node == null)
            return 0;
        else
            return (size(node.left) + 1 + size(node.right));
    }
}
public class BinaryTreeElements
{
        public static void main(String[] args) {
            BinaryTree t = new BinaryTree();
            t.root = new Node(10);
            t.root.left = new Node(25);
            t.root.right = new Node(30);
            t.root.left.left = new Node(50);
            t.root.left.right = new Node(45);
            System.out.println("Number of elements in binary tree: " + t.size());
        }
}

Output:

Number of elements in binary tree: 5

Note: If reader wants to copy and use the code provided in the answer, the reader has to make sure to replace [NBSP] with spaces, if found any in the code. Else the program may not compile/run successfully.


Related Solutions

write a recursive method that returns the product of all elements in java linked list
write a recursive method that returns the product of all elements in java linked list
Java Programm please! Design and implement an algorithm using recursion and backtracking to sort an array...
Java Programm please! Design and implement an algorithm using recursion and backtracking to sort an array of integers into ascending order. Consider the given array as input and produce a sorted array as output. Each time you take an integer from the input array, place it at the end of the output array. If the result is unsorted, backtrack.
Describe a way to use recursion to add all the elements in a n × n...
Describe a way to use recursion to add all the elements in a n × n (two dimensional) array of integers (java)
Data Structures ( Recursion ) Assignment Write a recursive method removeMiddle that receives an array list...
Data Structures ( Recursion ) Assignment Write a recursive method removeMiddle that receives an array list which has odd number of elements, then it deletes the element in the middle only. The method should receive only one parameter (the array list) The base case is when the array list has only one element, just remove that, otherwise, you need to remove the first one and the last one then call the method, then you need to add them again after...
1) a. Write a C++ program for the recursive algorithm that removes all occurrences of a...
1) a. Write a C++ program for the recursive algorithm that removes all occurrences of a specific character from a string b. Write the pseudocode for the program.
java 2D array / recursion explain every method You are requested to write a Java program...
java 2D array / recursion explain every method You are requested to write a Java program of a simple Memory Management Unit. The program should allow the following: 1. The user can create a process asking for memory. The program will return a process ID if the requested memory can be allocated. It will also print the allocated Base and Limit. 2. The user can delete a process by specifying a process ID. The program should do that and free...
5. (20 marks) Write a recursive Bubble Sort algorithm that takes an array A of n...
5. Write a recursive Bubble Sort algorithm that takes an array A of n numbers as input. Analyze its time complexity using a recursion tree. Implement your algorithm in Java
Part 1:Write a program in Java that declares an array of 5 elements and displays the...
Part 1:Write a program in Java that declares an array of 5 elements and displays the contents of the array. Your program should attempt to access the 6th element in the array (which does not exist) and using try. catch your program should prevent the run-time error and display your error message to the user. The sample output including the error message is provided below. Part (1) Printing an element out of bounds 5 7 11 3 0 You went...
Write a RECURSIVE algorithm (different from the ones your provided in 3) implemented in Java a...
Write a RECURSIVE algorithm (different from the ones your provided in 3) implemented in Java a in a complete Java program to reverse a stack of characters using recursion. You are not allowed to use loop constructs like while, for..etc, and you can only use the following functions on Stack S shown below (15pts) Provide an explanation of the running time. You will need to implement your own stack if needed isEmpty(S) push(S) pop(S) Make your own assumption and your...
Explain the benefits a recursive algorithm can provide. Discuss the negative aspects of using recursion.
Explain the benefits a recursive algorithm can provide. Discuss the negative aspects of using recursion.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT